Cannot load "unsafe" DLL - c#

I am trying to load a LabVIEW DLL in a dnxcore application. However the build of LabVIEW is very old, from 2009. So the maximum compatabillity is .NET 3.5. Therefore im using a class library that loads the DLL.
Now comes my exception. C# keeps complaining about not opening an assembly from a network location. Howver I have already set it as trusted but C# still does not trust it, probably has todo something with CAS Policies.
The fix for this issue should be setting the loadFromRemoteSources flag to true. However DNXCore does not default use xml config anymore. So tried it by JSON:
{
"runtime": {
"loadFromRemoteSources": {
"enabled" : true
}
}
}
However this not seem to fix it. I also tried by xml and loading it through the ConfigurationBuilder
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddXmlFile("app.config")
.AddEnvironmentVariables();
Configuration = builder.Build();
And the XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
</configuration>
So I was curious has anyone already experienced this and knows a fix for this? I know the DLL works since run it from a .NET 3.5 application which does not include the CAS Policy..

Related

Winform images (ResourceManager) not visible on Windows 10

I have a Windows form application that works fine on Windows 7, but when opened in Windows 10, image files using ResourceManager don't show up. Application is using .Net 3.5 framework. Following is a bit of code:
static readonly System.Resources.ResourceManager rm = new System.Resources.ResourceManager("ImageResources", Assembly.GetExecutingAssembly());
rm.GetObject("ImageName");
Following is the error:
Could not find any resources appropriate for the specified culture or
the neutral culture. Make sure was correctly embedded or linked into
assembly at compile time, or that all the satellite assemblies
required are loadable and fully signed.
System.Resources.MissingManifestResourceException:
Is it due to some kind of incompatibility or Windows 10 is somehow restricting ResourceManager class to use all those images?
Try to check value of Environment.Version (with some MessageBox for example) on the target machine.
If you get 4.0 then you need to change configuration file as was proposed by Dr. Stich.
If you don't have configuration file then create it like described there:
How to: Add an Application Configuration File to a C# Project
And change it content to something like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
</startup>
</configuration>
Runtime version you can get on supportedRuntime Element page
This issue was eventually resolved by adding CultureInfo.CurrentCulture in rm.GetObject method parameter i.e.
rm.GetObject("ImageName", CultureInfo.CurrentCulture);

which is the right way to connect couchbase in C#

I referred the document and it says
Get the client library by using one of the following methods:
Download the zip file from here.
Run the following command in the NuGet package manger console
I installed via NuGet package manger console
var client = new CouchbaseClient();
I didn't get reference for this class CouchbaseClient;
Am i doing wrong or how to rectify this ?
And the code which is working for me is ,
Cluster objCluster = new Cluster();;
IBucket objBucket = objCluster.OpenBucket();
var returnVal = objBucket.GetDocument<dynamic>("strKey").Content;
//For upserting
objBucket.Upsert(strkey, objDoc);
This is working for me.
Problem in this is :
All the inserts are falling into default bucket.
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="couchbase">
<section name="bucket-1" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase"/>
</sectionGroup>
</configSections>
<couchbase>
<bucket-1>
<servers bucket="default">
<add uri="http://10.0.0.1:8091/pools/default"/>
</servers>
</bucket-1>
</couchbase>
</configuration>
In that bucket="default" i changed default to other bucket. Still couldn't succeeded.
Please clarify me in two things:
What dll i need to use
And in the configuration what exactly i need to change ?
UPDATE :
If i removed the dll added via nuget and added via the one present in zip that class is coming.
But Still didn't succeeded in the config part and also why the change in nuget and the package.
Which one to follow ? The document is explained with dlls in zip.
NuGet and dll
CouchbaseClient is from older versions of the SDK (< 2.0). Latest NuGet package is indeed version 2+.
The snippet of code you provided is ok using SDK 2.0.
Where is the documentation you referred to? Where did you download the zip?
Client configuration and connecting to a non-default bucket
I'm not entirely sure about the client configuration's schema, but I don't think what you did does anything. OpenBucket() always opens the "default" bucket (hardcoded), and you should use OpenBucket(BucketName, BucketPassword) to open a different one.
Also, for the cluster to take your App.config into account at all, it must be created using the constructor that takes the config section as a parameter: new Cluster("couchbase/bucket-1");. This is usually useful for bootstrapping configuration ( tags) and choosing different ports / activating SSL, since the default constructor will only try to connect on localhost.
See the test configuration for examples.

Microsoft.Dynamics.BusinessConnectorNet mixed mode assembly error

"FileLoadException was unhandled by user code"
(Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information)
as the matter above.i got exception when try to execute
Axapta axapta;
AxaptaRecord axaptaRecord;
List<Vendor> vendors = new List<Vendor>();
public void Submit(Vendor vendor)
{
axapta = new Axapta();
axapta.Logon(null,null, null, null);
using (axaptaRecord = axapta.CreateAxaptaRecord("IDS_Pelajar"))
{
axaptaRecord.Clear();
axaptaRecord.InitValue();
axaptaRecord.set_Field("TenteraPolisNo", vendor.VendorAccount);
axaptaRecord.set_Field("Poskod", vendor.InvoiceAccount);
axaptaRecord.set_Field("Keturunan", vendor.Name);
axaptaRecord.Insert();
}
axapta.Logoff();
vendors.Add(vendor);
i already try to add this line of code in app.config
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
but still it doesn't work.
i have no problem to execute that block of code in console..the exception only pop up when i'm try to execute that block of code in WCF services library
sorry for trouble but i really loss now..Tq 4 help
Check if any of the below help you
Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information - Release Build
Handling Mixed Mode Assembly Error in WCF Service Host
Being WCF, I feel the 2nd link might prove useful. The config file for WCF Service host is located at C:\Program Files (x86)Microsoft Visual Studio 10.0Common7IDEWcfSvcHost.exe.config and hence making the change in this config file should fix it.
Hope this helps.

Microsoft.Windows.ActCtx on Windows Xp

These days I'm very much busy on developing an activex/com application. Some of our customers are working under heavily restricted windows environments. So i decided to make my application regfree. I found genman32.exe which can easily create manifests (also mt.exe is useful). Everything went fine but when i tried to execute my application from wsh(vbs or js) -which is obligated for my the situation because the application works on a com server-
set o = CreateObject("Application.Interface")
// No object reference
Because "CreateObject" looks to the registery and there is no registery entry :) then i searched and found the thing that is "actctx". It is very easy to implement in a dot.net environment. But i must execute my application from wsh(vbs or js) ;) so i decided to search a little then found
set o = CreateObject("Microsoft.Windows.ActCtx")
o.manifest = "L:\\Application.dll.manifest"
set app = o.CreateObject("Application.Interface")
app.Launch() // which is my executing function
Problem -
"Microsoft.Windows.ActCtx" interface is not available in Windows Xp machines even in SP3 - Microsoft never lets it easy -
Is there any solution to that problem? Do You know any other methods or windows update that creates that interface?
I figured out the problem with my manifest. I'll share it with anyone else who may have run into a similiar problem.
Please be aware that you MUST specify the progid="" property in your manifest when using this with the "Microsoft.Windows.ActCtx" interface otherwise you get ActiveX Component Can't Create Object error.
<comClass
clsid="{ED59F192-EF2E-4BCC-95EB-85A8C5C65326}"
progid="myclass.process"
threadingModel = "Apartment" />
The following manifest example should get you up and running :)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<assemblyIdentity
type="win32"
name="myclass"
version="1.0.0.0"/>
<file name = "myclass.dll">
<comClass
clsid="{ED59F192-EF2E-4BCC-95EB-85A8C5C65326}"
progid="myclass.process"
threadingModel = "Apartment" />
<typelib tlbid="{7AE20C3A-48C2-42C1-A68D-A1C3EB0A2C65}"
version="1.0" helpdir=""/>
</file>
<comInterfaceExternalProxyStub
name="_PROCESS"
iid="{187D0811-470D-44C0-B68C-C1C7F3EEFDA0}"
proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
baseInterface="{00000000-0000-0000-C000-000000000046}"
tlbid = "{7AE20C3A-48C2-42C1-A68D-A1C3EB0A2C65}" />
</assembly>
If the Microsoft.Windows.ActCtx were redistributable, there would have to be some way for it to get onto the machine and globally registered. If you had access to register this on the machine, can't you insted simply register Application.Interface? If you're dealing with a restricted environment ... well you have to deal with what's available already.
It looks like you're using the wsh script to launch your application. Why not write a stub to launch the app in native or managed code (where you will be able to use a manifest), and call that stub instead?

.NET Configuration (app.config/web.config/settings.settings)

I have a .NET application which has different configuration files for Debug and Release builds. E.g. the debug app.config file points to a development SQL Server which has debugging enabled and the release target points to the live SQL Server. There are also other settings, some of which are different in debug/release.
I currently use two separate configuration files (debug.app.config and release.app.config). I have a build event on the project which says if this is a release build then copy release.app.config to app.config, else copy debug.app.config to app.config.
The problem is that the application seems to get its settings from the settings.settings file, so I have to open settings.settings in Visual Studio which then prompts me that the settings have changed so I accept the changes, save settings.settings and have to rebuild to make it use the correct settings.
Is there a better/recommended/preferred method for achieving a similar effect? Or equally, have I approached this completely wrong and is there a better approach?
Any configuration that might differ across environments should be stored at the machine level, not the application level. (More info on configuration levels.)
These are the kinds of configuration elements that I typically store at the machine level:
Application settings
Connection strings
retail=true
Smtp settings
Health monitoring
Hosting environment
Machine key
When each environment (developer, integration, test, stage, live) has its own unique settings in the c:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG directory, then you can promote your application code between environments without any post-build modifications.
And obviously, the contents of the machine-level CONFIG directory get version-controlled in a different repository or a different folder structure from your app. You can make your .config files more source-control friendly through intelligent use of configSource.
I've been doing this for 7 years, on over 200 ASP.NET applications at 25+ different companies. (Not trying to brag, just want to let you know that I've never seen a situation where this approach doesn't work.)
This might help some people dealing with Settings.settings and App.config: Watch out for GenerateDefaultValueInCode attribute in the Properties pane while editing any of the values in the Settings.settings grid in Visual Studio (Visual Studio 2008 in my case).
If you set GenerateDefaultValueInCode to True (True is the default here!), the default value is compiled into the EXE (or DLL), you can find it embedded in the file when you open it in a plain text editor.
I was working on a console application and if I had defaulted in the EXE, the application always ignored the configuration file placed in the same directory! Quite a nightmare and no information about this on the whole Internet.
There is a related question here:
Improving Your Build Process
Config files come with a way to override the settings:
<appSettings file="Local.config">
Instead of checking in two files (or more), you only check in the default config file, and then on each target machine, you put a Local.config, with just the appSettings section that has the overrides for that particular machine.
If you are using config sections, the equivalent is:
configSource="Local.config"
Of course, it's a good idea to make backup copies of all the Local.config files from other machines and check them in somewhere, but not as a part of the actual solutions. Each developer puts an "ignore" on the Local.config file so it doesn't get checked in, which would overwrite everyone else's file.
(You don't actually have to call it "Local.config", that's just what I use)
From what I am reading, it sounds like you are using Visual Studio for your build process. Have you thought about using MSBuild and Nant instead?
Nant's xml syntax is a little weird but once you understand it, doing what you mentioned becomes pretty trivial.
<target name="build">
<property name="config.type" value="Release" />
<msbuild project="${filename}" target="Build" verbose="true" failonerror="true">
<property name="Configuration" value="${config.type}" />
</msbuild>
<if test="${config.type == 'Debug'}">
<copy file=${debug.app.config}" tofile="${app.config}" />
</if>
<if test="${config.type == 'Release'}">
<copy file=${release.app.config}" tofile="${app.config}" />
</if>
</target>
To me it seems that you can benefit from the Visual Studio 2005 Web Deployment Projects.
With that, you can tell it to update/modify sections of your web.config file depending on the build configuration.
Take a look at this blog entry from Scott Gu for a quick overview/sample.
We used to use Web Deployment projects but have since migrated to NAnt. Instead of branching and copying different setting files we currently embed the configuration values directly in the build script and inject them into our config files via xmlpoke tasks:
<xmlpoke
file="${stagingTarget}/web.config"
xpath="/configuration/system.web/compilation/#debug"
value="true"
/>
In either case, your config files can have whatever developer values you want and they'll work fine from within your dev environment without breaking your production systems. We've found that developers are less likely to arbitrarily change the build script variables when testing things out, so accidental misconfigurations have been rarer than with other techniques we've tried, though it's still necessary to add each var early in the process so that the dev value doesn't get pushed to prod by default.
My current employer solved this issue by first putting the dev level (debug, stage, live, etc) in the machine.config file. Then they wrote code to pick that up and use the right config file. That solved the issue with the wrong connection string after the app gets deployed.
They just recently wrote a central webservice that sends back the correct connection string from the value in the machine.config value.
Is this the best solution? Probably not, but it works for them.
One of the solutions that worked me fine was using a WebDeploymentProject.
I had 2/3 different web.config files in my site, and on publish, depending on the selected configuration mode (release/staging/etc...) I would copy over the Web.Release.config and rename it to web.config in the AfterBuild event, and delete the ones I don't need (Web.Staging.config for example).
<Target Name="AfterBuild">
<!--Web.config -->
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Release.config" DestinationFiles="$(OutputPath)\Web.config" />
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Staging|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Staging.config" DestinationFiles="$(OutputPath)\Web.config" />
<!--Delete extra files -->
<Delete Files="$(OutputPath)\Web.Release.config" />
<Delete Files="$(OutputPath)\Web.Staging.config" />
<Delete Files="#(ProjFiles)" />
</Target>
You'll find another solution here: Best way to switch configuration between Development/UAT/Prod environments in ASP.NET? which uses XSLT to transfor the web.config.
There are also some good examples on using NAnt.
Our project has the same issue where we had to maintain configs for dev, qa, uat and prod. Here is what we followed (only applies if you are familiar with MSBuild):
Use MSBuild with the MSBuild Community tasks extension. It includes the 'XmlMassUpdate' task that can 'mass-update' entries in any XML file once you give it the correct node to start with.
To Implement:
1) You need to have one config file which will have your dev env entries; this is the config file in your solution.
2) You need to have a 'Substitutions.xml' file, that contains only the entries that are DIFFERENT (appSettings and ConnectionStrings mostly) for each environment. Entries that do not change across the environment need not be put in this file. They can live in the web.config file of the solution and will not be touched by the task
3) In your build file, just call the XML mass update task and provide the right environment as a parameter.
See example below:
<!-- Actual Config File -->
<appSettings>
<add key="ApplicationName" value="NameInDev"/>
<add key="ThisDoesNotChange" value="Do not put in substitution file" />
</appSettings>
<!-- Substitutions.xml -->
<configuration xmlns:xmu="urn:msbuildcommunitytasks-xmlmassupdate">
<substitutions>
<QA>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInQA"/>
</appSettings>
</QA>
<Prod>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInProd"/>
</appSettings>
</Prod>
</substitutions>
</configuration>
<!-- Build.xml file-->
<Target Name="UpdateConfigSections">
<XmlMassUpdate ContentFile="Path\of\copy\of\latest web.config" SubstitutionsFile="path\of\substitutionFile" ContentRoot="/configuration" SubstitutionsRoot="/configuration/substitutions/$(Environment)" />
</Target>
replace '$Environment' with 'QA' or 'Prod' based on what env. you are building for. Note that you should work on a copy of a config file and not the actual config file itself to avoid any possible non-recoverable mistakes.
Just run the build file and then move the updated config file to your deployment environment and you are done!
For a better overview, read this:
http://blogs.microsoft.co.il/blogs/dorony/archive/2008/01/18/easy-configuration-deployment-with-msbuild-and-the-xmlmassupdate-task.aspx
Like you I've also set up 'multi' app.config - eg app.configDEV, app.configTEST, app.config.LOCAL. I see some of the excellent alternatives suggested, but if you like the way it works for you, I'd add the following:
I have a
<appSettings>
<add key = "Env" value = "[Local] "/>
for each app I add this to the UI in the titlebar:
from ConfigurationManager.AppSettings.Get("Env");
I just rename the config to the one I'm targetting (I have a project with 8 apps with lots of database/wcf config against 4 evenioments). To deploy with clickonce into each I change 4 seetings in the project and go. (this I'd love to automate)
My only gotcha is to remember to 'clean all' after a change, as the old config is 'stuck' after a manual rename. (Which I think WILL fix you setting.setting issue).
I find this works really well (one day I'll get time to look at MSBuild/NAnt)
Web.config:
Web.config is needed when you want to host your application on IIS. Web.config is a mandatory config file for IIS to configure how it will behave as a reverse proxy in front of Kestrel. You have to maintain a web.config if you want to host it on IIS.
AppSetting.json:
For everything else that does not concern IIS, you use AppSetting.json.
AppSetting.json is used for Asp.Net Core hosting. ASP.NET Core uses the "ASPNETCORE_ENVIRONMENT" environment variable to determine the current environment. By default, if you run your application without setting this value, it will automatically default to the Production environment and uses "AppSetting.production.json" file. When you debug via Visual Studio it sets the environment to Development so it uses "AppSetting.json". See this website to understand how to set the hosting environment variable on Windows.
App.config:
App.config is another configuration file used by .NET which is mainly used for Windows Forms, Windows Services, Console Apps and WPF applications. When you start your Asp.Net Core hosting via console application app.config is also used.
TL;DR
The choice of the configuration file is determined by the hosting environment you choose for the service. If you are using IIS to host your service, use a Web.config file. If you are using any other hosting environment, use an App.config file.
See Configuring Services Using Configuration Files documentation
and also check out Configuration in ASP.NET Core.
It says asp.net above, so why not save your settings in the database and use a custom-cache to retrieve them?
The reason we did it because it's easier (for us) to update the continuously database than it is to get permission to continuously update production files.
Example of a Custom Cache:
public enum ConfigurationSection
{
AppSettings
}
public static class Utility
{
#region "Common.Configuration.Configurations"
private static Cache cache = System.Web.HttpRuntime.Cache;
public static String GetAppSetting(String key)
{
return GetConfigurationValue(ConfigurationSection.AppSettings, key);
}
public static String GetConfigurationValue(ConfigurationSection section, String key)
{
Configurations config = null;
if (!cache.TryGetItemFromCache<Configurations>(out config))
{
config = new Configurations();
config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
}
var result = (from record in config
where record.Key == key
select record).FirstOrDefault();
return (result == null) ? null : result.Value;
}
#endregion
}
namespace Common.Configuration
{
public class Configurations : List<Configuration>
{
#region CONSTRUCTORS
public Configurations() : base()
{
initialize();
}
public Configurations(int capacity) : base(capacity)
{
initialize();
}
public Configurations(IEnumerable<Configuration> collection) : base(collection)
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud; // Db-Access layer
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
}
/// <summary>
/// Lists one-to-many records.
/// </summary>
public Configurations List(ConfigurationSection section)
{
using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_MyConfiguration"))
{
_crud.Db.AddInParameter(dbCommand, "#Section", DbType.String, section.ToString());
_crud.List(dbCommand, PopulateFrom);
}
return this;
}
public void PopulateFrom(DataTable table)
{
this.Clear();
foreach (DataRow row in table.Rows)
{
Configuration instance = new Configuration();
instance.PopulateFrom(row);
this.Add(instance);
}
}
#endregion
}
public class Configuration
{
#region CONSTRUCTORS
public Configuration()
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud;
public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
Clear();
}
public void Clear()
{
this.Section = "";
this.Key = "";
this.Value = "";
}
public void PopulateFrom(DataRow row)
{
Clear();
this.Section = row["Section"].ToString();
this.Key = row["Key"].ToString();
this.Value = row["Value"].ToString();
}
#endregion
}
}

Categories