Silverlight 4, subclassing WebClient - silverlight

Following an advice, I saw at several web pages (for example Using CookieContainer with WebClient class), I subclassed WebClient class to use a cookie with it:
public class MyWebClient : System.Net.WebClient
{
}
Now, when I initialize MyWebClient:
MyWebClient wc = new MyWebClient();
it throws TypeLoadException. My OS is Windows 7 (japanese), so error message is not in english; I see it is related to security rules. What might be the problem?

WebClient's constructor is marked with the SecuritySafeCritical attribute. And it looks like that is what is causing the security exception. I tried applying that same attribute to MyWebClient's constructor but that didn't work. From what I've read, this kind of thing just isn't allowed in Silverlight. For example, see this other question.
For reference, the exact exception message is:
System.TypeLoadException
Inheritance security rules violated while
overriding member: 'MyWebClient..ctor()'. Security accessibility of
the overriding method must match the security accessibility of the
method being overriden.
I wish there was a better answer...

You need to implement a default constructor with the SecuritySafeCritical attribute. Had this problem today and that was the solution.
public class MyWebClient : System.Net.WebClient
{
[SecuritySafeCritical]
public MyWebClient() : base() {}
}

Related

Nancyfx localization

I'm testing localization in Nancy and able to get it to work using EMBEDDED resource files but the issue is I don't want embedded resource files because I want them to be allowed to be edited via the GUI or using the file (if I go the DB route or setting the resource file as "content").
According to the doucmentation you should be able to override it to support using a database but I'm unable to get this to work (https://github.com/NancyFx/Nancy/wiki/Localization):
public class ResourceManager : ResourceBasedTextResource
{
public ResourceManager(IResourceAssemblyProvider resourceAssemblyProvider) : base(resourceAssemblyProvider)
{
}
public new string this[string key, NancyContext context]
{
get
{
return "HELO!";
}
}
}
This was just me messing around but I was hoping in the Razor view when I did #Text.Localization. it should return "HELO!" for everything... however it is not working
There really isn't a question in your post so I'm going to have to guess a bit and assume that you're not getting any exception but rather you're not seeing the "HELO!" in your view
Simply implementing a new ResourceBasedTextResource class is not enough. This is a core component and as such you are going to explicitly have to tell Nancy to use it. You do this by overriding the InternalConfiguration property of your Bootstrapper and tell Nancy to use your implementation instead
You can see it in the DemoBootstrapper of the demo that is linked from that wiki page https://github.com/NancyFx/Nancy/blob/8970ac9d6c7cf46e6060f0b83117c19fa18085c2/src/Nancy.Demo.Razor.Localization/DemoBootstrapper.cs#L11
Also, if you are not going to use resource files, then you should look into inheriting from ITextResource interface instead. It's a simple interface so it should be straight forward.
HTH

UriFormatException : Invalid URI: Invalid port specified

The assembly qualified string used as a parameter below for a Uri works in XAML, but gives me the error shown when used in code.
I tried every kind of UriKind with the same result. How can I fix this?
[Test]
public void LargeImageSource_IsKnown()
{
var uri = new Uri(
"pack://application:,,,/" +
"MyAssembly.Core.Presentation.Wpf;component/" +
"Images/Delete.png", UriKind.RelativeOrAbsolute);
Assert.That(
_pickerActivityCollectionVm.DeleteActivityCommand.LargeImageSource,
Is.EqualTo(uri));
}
System.UriFormatException : Invalid URI: Invalid port specified.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
UPDATE
Based on Thomas' superb answer and my own comments about readability, I wound up using the following in my BaseTestFixture class. Hope this helps someone else.
protected virtual void OnFixtureSetUp() {
// logging, other one time setup stuff...
const string scheme = "pack";
if (!UriParser.IsKnownScheme(scheme)) {
Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme));
}
}
That's because you're executing this code while the pack:// scheme is not yet registered. This scheme is registered when you create the Application object. You can add this code in the setup of your test fixture:
[SetUp]
public void Setup()
{
if (!UriParser.IsKnownScheme("pack"))
new System.Windows.Application();
}
EDIT: actually it seems the pack:// scheme is registered in the type initializer of the PackUriHelper class (which happens to be used by the Application class). So actually you don't need to create an instance of Application, you only need to access a static member of PackUriHelper to ensure the type initializer has run:
[SetUp]
public void Setup()
{
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
}
It appears that accessing PackUriHelper.UriSchemePack only registers the pack scheme, not the application scheme, which I needed to use the pack://application:,,,/ syntax in my unit tests. I therefore had to use the new Application() approach, which worked fine for registering both schemes.
If you're seeing this error in a Windows Store / WinRT project:
I wasn't able to use the "pack://" syntax at all when trying to load a resource in my C# app. What worked was ms-appx:// syntax of this kind:
ms-appx://[project folder]/[resource path]
For example, I wanted to load a resource dictionary named "styles.xaml" from a folder "core". This URI ended up working for me:
dictionary.Source = new System.Uri("ms-appx:///core/styles.xaml");
Even though the question specified WPF, the problem seemed extremely similar but ended up having a completely different solution, which took a while to find, and existing answers didn't help at all.
Again, this solution does not apply to WPF

Why Don't DomainService Constructor Overloads Show Up as DomainContext Constructor Overloads?

I wrote an overload for my DomainService class. Problem is, when I recompile, it's not showing up as an overload for my DomainContext. What's wrong? Here is a code sample:
[EnableClientAccess]
public class FoodDomainService : LinqToEntitiesDomainService<FoodEntities>
{
public FoodDomainService(CultureInfo cultureInfo)
{
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
}
And this doesn't work:
FoodDomainContext _foodContext = new FoodDomainContext(Thread.CurrentThread.CurrentCulture);
I get an error that there is no overload matching that. Am I not allowed to do this? Do I need an attribute of some kind?
You are not allowed to do this. When newing up the context from your Silverlight client, you are not directly intantiating your service. Instead, you instantiate a proxy class that was generated by RIA Services, and that proxy class will then call your service. This is why you don't see your constructor: because RIA did not generate it in your proxy.
Doing what you're trying to do would also implicate that there is a round-trip to the server at the time of newing up that FoodDomainContext class, which is not going to happen, because you need to complete the initialisation of that object before you can do so.
Anyway, instead of that you can create a method called SetCurrentCulture() and then call it after initializing the proxy.
This will not work because DomainContext is generated on client code of silverlight, click on view all folders or jump to definition and you will see that code generated will not contain your extra constructor.
Instead you will have to create a method in your domain service and pass information to server.
public SetCultreInfo(int lang,...)
{
.. set culture info
}
On your client, inside constructor you should call,
public MyDomainContext()
{
this.SetCulture(....);
}

Issue intercepting property in Silverlight application

I am using Ninject as DI container in a Silverlight application. Now I am extending the application to support interception and started integrating DynamicProxy2 extension for Ninject. I am trying to intercept call to properties on a ViewModel and ending up getting following exception:
“Attempt to access the method failed: System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Reflection.Module, Boolean)”
This exception is thrown when invocation.Proceed() method is called. I tried two implementations of the interceptor and they both fail
public class NotifyPropertyChangedInterceptor: SimpleInterceptor
{
protected override void AfterInvoke(IInvocation invocation)
{
var model = (IAutoNotifyPropertyChanged)invocation.Request.Proxy;
model.OnPropertyChanged(invocation.Request.Method.Name.Substring("set_".Length));
}
}
public class NotifyPropertyChangedInterceptor: IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
var model = (IAutoNotifyPropertyChanged)invocation.Request.Proxy;
model.OnPropertyChanged(invocation.Request.Method.Name.Substring("set_".Length));
}
}
I want to call OnPropertyChanged method on the ViewModel when property value is set.
I am using Attribute based interception.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class NotifyPropertyChangedAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
if(request.Method.Name.StartsWith("set_"))
return request.Context.Kernel.Get<NotifyPropertyChangedInterceptor>();
return null;
}
}
I tested the implementation with a Console Application and it works alright.
I also noted in Console Application as long as I had Ninject.Extensions.Interception.DynamicProxy2.dll in same folder as Ninject.dll I did not have to explicitly load DynamicProxy2Module into the Kernel, where as I had to explicitly load it for Silverlight application as follows:
IKernel kernel = new StandardKernel(new DIModules(), new DynamicProxy2Module());
Could someone please help? Thanks
Reflection can be really tricky in silverlight because of security issues.
Check Gabe's answer for this question, it's the same problem.
The good news is that you can achieve the same functionality you want using dynamic instead of proxies. Just extend your ViewModel from DynamicObject and override the TrySetMember method.
I hope it helps :)

AppDomain.GetData method not accessible?

I am developing a Silverlight 3 application and I would like to delegate all unexpected error handling in a single instance of a class I have named ErrorHandler. This class has one method named HandleApplicationException, plus a couple of other methods to handle more specialized errors.
In my application I am using Unity for dependency injection, but since I want the error handling object to be available even when the Unity container is not yet set up, I register the object as AppDomain global data in the App class constructor, this way:
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
AppDomain.CurrentDomain.SetData("ErrorHandler", new ErrorHandler());
InitializeComponent();
}
And in case of unhandled exception, I retrieve the error handler object and use it this way:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
e.Handled = true;
var errorHandler = AppDomain.CurrentDomain.GetData("ErrorHandler") as ErrorHandler;
Debug.Assert(errorHandler != null, "No ErrorHandler registered.");
errorHandler.HandleApplicationException(e.ExceptionObject);
}
The problem is that the AppDomain.GetData method in the Application_UnhandledException method is throwing a MethodAccessException. I don't understand why, as I am just invoking a public method on the AppDomain class. I have used a similar approach in other applications and it worked fine (anyway these were not Silverlight applications).
So, what's going on? Am I doing something wrong?
Ok, I got it. From MSDN documentation:
This member has a
SecurityCriticalAttribute attribute,
which restricts it to internal use by
the .NET Framework for Silverlight
class library. Application code that
uses this member throws a
MethodAccessException.
I have resorted to storing the error handler in a public property in the App class, then I access it using ((App)Application.Current).ErrorHandler. I don't like doing things this way but I suppose it is ok in this special case.
Why can't you just use a static instance of ErrorHandler? I.e. have something like ErrorHandler.Current?
It looks like you're trying to manually construct a poor man's IoC framework to be honest.
Consider doing some research on Unity/Ninject and see for yourself why strongly-typed decoupling is better.

Resources