Possible to reference System.Web.HttpUtility.JavaScriptStringEncode(...) method in PCL project?

I have a Portable Class Library project which targets Xamarin.Android and Xamarin.iOS. I'd like to reference/call the System.Web.HttpUtility.JavaScriptStringEncode(...) method to encode a string to be passed into a JavaScript function. Is this possible? Or is there a similar method that I could reference?

Posts

  • PeterDavisPeterDavis USMember ✭✭✭
    edited April 2014

    You can't do it directly from your PCL. Here's how I handle these sorts of things: In my PCL, I define an interface:

    public interface IJavaScriptStringEncoder
    {
       string EncodeString(string value);
    }
    

    Then create a class in your PCL:

    public static JavaScriptEncoderManager
    {
        public static IJavaScriptStringEncoder Encoder { get; set; }
    }
    

    In both your Android and iOS apps, you would implement IJavaScriptStringEncoder in a class.

    public class JavaScriptStringEncoder : IJavaScriptStringEncoder
    {
        public string EncodeString(string value)
        {
            return System.Web.HttpUtility.JavaScriptStringEncode(value):
        }
    }
    

    And then when your Android and iOS apps start up, from the Android or iOS app simply do:

    JavaScriptEncoderManager.Encoder = new JavaScriptStringEncoder();
    

    And then from your PCL, when you need to call it, all you need to do is:

    string myStr = JavaScriptEncoderManager.Encoder.EncodeString(myString);
    

    An IoC container will also work beautifully for this (which is actually what I use), but you can do the JavaScriptEncoderManager class instead if you don't want to add an IoC container. But the concepts are similar.

  • AdilHussainAdilHussain GBMember ✭✭

    Hi Peter, thanks for the response. I guess this will work but won't it essentially duplicate code (i.e. having identical copies of JavaScriptStringEncoder in my Android and iOS projects) and go against the primary reason of using a Portable Class Library project in the first place?

  • PeterDavisPeterDavis USMember ✭✭✭
    edited April 2014

    In this case, yes, it would be the same. You could use a file link to share the same implementation file, but I don't think I would.

    Normally, this sort of solution for cross-platform stuff doesn't result in identical code. For example, I have an ILogger interface that I implement in Android and iOS. In Android it logs to logcat and in iOS, it logs to a SQLite table.

    Code duplication can be a maintenance issue, but in this case the implementation is so trivial, it's hardly worth the concern.

Sign In or Register to comment.