FileInfo..ctor(string fileName) throwing exception: bug in SL 4.0 or .NET 4.0? - .net-4.0

The following test case passes in .NET 4.0:
var fiT = new FileInfo("myhappyfilename");
Assert.IsNotNull(fiT);
... but fails in Silverlight 4.0 with the following error:
System.ArgumentNullException: Value cannot be null.
Parameter name: format
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.Environment.GetResourceString(String key, Object[] values)
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileInfo.Init(String fileName, Boolean checkHost)
at System.IO.FileInfo..ctor(String fileName)
Either the failure is a bug in SL 4.0, or the non-failure is a bug in .NET 4.0. Anyone know which it is?
(For the record, I'm running SL 4.0 on VS 2010 RC, which may be contributing to the problem).

See the MSDN documentation for FileInfo for Siverlight 4:
When it is called by an elevated-trust
application, provides instance methods
for the creation, copying, deletion,
moving, and opening of files, and aids
in the creation of FileStream objects.
This class cannot be inherited.
Chances are your application isn't running with elevated trust. If you want to access those restricted methods, it'll need to be.
As to why it's returning a null - that may well be a bug, possibly an improperly propagated SecurityException. Then again, it may be as designed - the docs are also still pre-release. EDIT: gabe's answer is most likely correct on this point.

Since you generally can't access the filesystem from Silverlight (you need a fully-trusted OOB app), it looks like SL4 is trying to throw an exception, but is failing because the text for that exception isn't available in the SL4 beta. Presumably you would get the correct exception once SL4 is released.

Related

Error in 3rd Party Library Causing Hanging in Release

My main program is an ASP.Net Core Web API that has a third party library in a hosted service. The third party library is initializing fine but then it throws some errors sometime throughout its lifecycle.
It supplies a way of hooking into the object via an event and will let me know what the error is so that I can handle it but it still throws in the third party library..
Since I am handling the event myself, I want to completely ignore these errors that are occurring in this library. Is there anyway that I can do that?
I have already tried to add a global exception handler and the strange thing is, this exception handler never gets hit. The only way I can get the exception is to set my exception settings to break when CLR exceptions happen like in the picture above
This does not crash my program. For some reason, the program just hangs. When I turn off CLR exceptions in the "Break when thrown" window, then the program runs just fine. It is almost like visual studio is doing something special to handle these types of exceptions that a console version cannot do
The only way that I can seem to get a console version of this running, is attach a visual studio debugger to the process and when the exception is hit, press the green play button "Continue" in visual studio. Otherwise the application just seems to hang on the exception being thrown by the third party library.
The application will run fine as long as visual studio is attached and the CLR break exceptions are not checked
Does anyone know how to make sure that these types of exceptions do not hang the program when released?
Additional Info:
The third party library is a .NET Framework 4 library
The Asp.Net project is targetting "net5.0-windows"
The 3rd party class is probably using multi-threading
if it helps, this is how I am creating the third party class
Handling NullReferenceException in release code(Official advice)
It's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. A NullReferenceException is often a non-recoverable error. In these cases, letting the exception stop the app might be the best alternative.
However, there are many situations where handling the error can be useful:
1.Your app can ignore objects that are null. For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Recording the bad data in a log file or in the application UI might be all you have to do.
2.You can recover from the exception. For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again.
3.You can restore the state of your app to a valid state. For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app.
4.You want to report the exception. For example, if the error was caused by a mistake from the user of your app, you can generate a message to help them supply the correct information. You can also log information about the error to help you fix the problem. Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs.
So after days of research I've finally found an event to hook into to give you error messages from ANY source no matter how many level deep you go in threads.
AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
Hooking into this event it will allow you to see errors from every library and every thread. Simply place the above into you program.cs (or whatever startup file you have) and magically you will be flooded with all of the unknown errors from all of the 3rd party libraries you thought were once flawless.
private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
Console.WriteLine(e.Exception.Message, e.Exception.StackTrace);
}
I've done so with the following method and low and behold. The third party library was trying to reference another project in an unsafe way and throwing an error. Since I didn't need this other project reference the built exe did not have a reference to this assembly because I had no direct reference to it in the project (darn smarty pants who need to optimize everything). I was able to run correctly because in my visual studio solution, I had a reference to this other project. So the third party library would pick up on it as soon as visual studio connected with the debugger through some sort of dark magic.
Anyways, I made a throw away object that used the project that was required and the issue was solved.
I really hope that this helps someone else and saves them the days it took me to find this.

Exception in xaml while opening the Silverlight 4 project

Today i encounter a strange thing. Yesterday all my code was working fine i test it twice before shutting down my pc. Today when i try to open my project exception arrives
"System.NullReferenceException
Object reference not set to an instance of an object."
I searched for the solutions, but none works for me. I did not upgrade silverlight version, i start my work with silverlight 4 and cuurently i am using the same.
Here is the stack trace for the exception:
System.NullReferenceException
Object reference not set to an instance of an object.
at Microsoft.Windows.Design.Platform.SilverlightMetadataContext.SilverlightXamlExtensionImplementations.d__8.MoveNext()
at MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption()
at MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(Identifier identifier)
at MS.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope, IParseContext context)
at MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement parent, PrefixScope parentScope, IParseContext context, IMarkupSourceProvider provider)
at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors)
at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem()
at Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem()
at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState()
at MS.Internal.Host.PersistenceSubsystem.Load()
at MS.Internal.Host.Designer.Load()
at MS.Internal.Designer.VSDesigner.Load()
at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load()
at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view)
at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view)
at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view)
at MS.Internal.Host.Isolation.IsolatedDesigner.Load()
Hopefully your suggestions will solve my problem.
After trying for 3-4 hours i go for simple aproach and it works!
Here is what i do:
Go to Add/Remove Program and uninstall all silverlight application, all of them.
Rebbot my pc, install SL4 tools, SL4 Toolkit and SL4 Developer runtime.
Make sure that you change the option for SL4 to update its version automatically.
Another reboot and it's done
I suspect that as i did not change the default setting so SL4 updated itself to SL5 without notifying me :)
Make sure to disable automatic updates.

Cast causes "Operation could destabilize the runtime" on one ASP.NET 4.0 box and not another

Here's (part of) a simple deserialization method that I've used in .NET 2.0 for years. T is an unconstrained type parameter.
protected virtual T ItemFromString(string s) {
if (typeof(T).IsPrimitive ||
typeof(T) == typeof(string)) {
try {
// needed for string, too: compiler doesn't allow (T)s
return (T)Convert.ChangeType(s, typeof(T));
}
catch (Exception ex) {
// stuff
}
}
}
I changed the application pool to run in 4.0, and everything was fine — until I deployed it to the remote server. There, I get "Operation could destabilize the runtime" on the line
return (T)Convert.ChangeType(s, typeof(T));
(Actually the line reported is the ending brace of the method, but I've narrowed it down to that line.)
The problem goes away if I change the runtime back to 2.0.
The runtime versions are both 4.0.30319. The app is otherwise identical, including web.config. Both apps using shared application pools and running in Full trust. Presumably another setting is affecting it, but I have no idea how to figure out what.
Everything I've found about this involves Reflection.Emit or covariance, which I'm not using.
Any leads?
Thanks.
Now that this question has been viewed 0x80 times, I'll post the solution I recently used when I could no longer put off the move to .NET 4.
You have to target the .NET 4 platform in the build, and set the following assembly property.
using System.Security;
// Needed to enable generic deserialization in partial trust.
[assembly: SecurityRules(SecurityRuleSet.Level1)]
I'd commented that I was in full trust mode, but I must have been wrong about that. This is only an issue in partially-trusted environments.

.NET 4.0 AppDomain: obsoleted Evidence

I am a .NET student and currently we are learning about Application Domains.
We were given the following example code (for .NET 3.5). As expected, it throws a SecurityException. Note: TestApp.exe is added as a reference in the project.
Dim file As String = "TestApp.exe"
Dim hostEvidence As Object() = {New Zone(SecurityZone.Internet)}
Dim appDomainEvidence As Evidence = New Evidence(hostEvidence, Nothing)
Dim d As AppDomain = AppDomain.CreateDomain("MyDomain", appDomainEvidence)
d.ExecuteAssembly(file)
When trying to run this in VS2010 under .NET 4.0 I run into a problem.
First it shows a warning
'Public Sub New(hostEvidence() As Object, assemblyEvidence() As Object)' is obsolete: 'This constructor is obsolete. Please use the constructor which takes arrays of EvidenceBase instead.'.
I change the type of hostEvidence to EvidenceBase() and the warning is gone.
However, when trying to run the application it gives an error.
This method implicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information.
I have viewed the page, followed the link to How to: Run Partially Trusted Code in a Sandbox and read http://blogs.msdn.com/shawnfa/archive/2009/05/27/coding-with-security-policy-in-net-4-0-implicit-uses-of-cas-policy.aspx but I'm having trouble understanding all of this.
The code example on MSDN is quite big compared to what I currently have, so any help with changing my code so it works without adding other stuff, will be very appreciated.
As it says in the link you provided, .NET is no longer supporting the policy portion of the code access security framework, as of version 4.0.
In other words, your lesson is about .NET 3.5 and does not pertain to the 4.0 framework. The solution is to revert to your original code and configure your project to target the 3.5 framework (you can still use Visual Studio 2010).
.

.NET 4.0 - CultureNotFoundException

I have migrated my ASP.NET MVC 2 project to VS 2010 + .NET 4.0.
Now when i start the application i get a lot of "CultureNotFoundException" in IntelliTrace and Output/Gebug window :
A first chance exception of type 'System.Globalization.CultureNotFoundException' occurred in mscorlib.dll
I know what "A first chance exception" means, but when i try to debug(added "CultureNotFoundException" into Bebug/Exceptions[Thrown]) why ex. is thrown i got this detailed exception text:
System.Globalization.CultureNotFoundException occurred
Message=Culture is not supported.
Parameter name: name
designer is an invalid culture identifier.
Source=mscorlib
ParamName=name
InvalidCultureName=designer
StackTrace:
at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
InnerException:
I wonder why .NET is trying to create CultureInfo with name "designer"?
Isn't it bug?
I had a similar issue with the CultureName "UserCache". To resolve this I deleted all the folders from in here:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
For other people that have this problem, this is usually an exception that is ignored.
Go to the Debug menu -> Exceptions... and ensure that you have everything unchecked for the Exception list.
This is actually by design in System.Web (at least up until .NET Framework v4.0), not necessarily the best approach, but it works.
You can find a more detailed description here, but it basically happens because ASP.NET checks every single folder to see if it contains satellite assemblies, and throws an exception otherwise.
Given that satellite assemblies live in folders with predictable names, one would wonder why they would decide to do this rather than only check folders that match the pattern, particularly since handling exceptions is rather expensive computationally compared to a simple conditional check.
I was curious as to the cause to see if there was something I could personally do to eliminate this particular annoyance.
The Exception is a side effect of calling, "System.Web.UI.Util.IsCultureName(name)"
The first time it's called in my MVC3 application is in regards to a directory called "UserCache", which is in the same directory as several directories with the expected culture names "en-US", etc. .Net is trying to find Satellite directories for the application.
It's called multiple times, even relating to files that are culture files, "EditorLocalization.bg-BG.designer.cs" for example (actually all of these that are in App_GlobalResources). [ What the code does here is to take all the files in App_GlobalResources, and see if the file ends in a CultureName, again calling IsCultureName.
So there's nothing you can really do to avoid this... In production where the .cs classes won't be there, perhaps it won't happen. It certainly slows down startup quite a bit, though!
In any case, in my mind it's a total bug that Microsoft throws an exception inside, "IsCultureName().
Go to the Debug -> Options in Visual Studio and check "Just My Code".
I found that turning on "Enable Just My Code" in the Debugging section of the Visual Studio 2017 options worked for me. That just hides those exceptions, which are part of the normal operation of the framework.
I had a similar issue with the "CultureNotFoundException". To resolve this I had to delete all the folders from in here additionally:
%LocalAppData%\Local\Temp\Temporary ASP.NET Files
Deleting from here wasn't enough:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
I had this error message:
'ViewBag.XXXXX' threw an exception of type 'System.Globalization.CultureNotFoundException' dynamic {System.Globalization.CultureNotFoundException}
The inner message said:
The culture is not supported.\r\nParameter name: name\r\nneutral is an invalid identifier culture.
The problem was that there was an invalid definition of the assembly culture in the AssemblyInfo.cs file:
[assembly: AssemblyCulture("neutral")]
To fix it, just leave empty the "culture" parameter like this:
[assembly: AssemblyCulture("")]
That fixed the problem for me.
I think it's the actual designer that messed things up. Try searching across your solution for "designer" string to see if any XML/HTML attributes have their values set to this string.
It seems as the problem was a bug in VS 2010 Beta 2.