Jaiprakash

  • valueOf and toString

    My colleague SDET Titus Chandramohan sent me a mail and reported a inconsistent bahavior in JScript. The issue he reported was...

     

    var f = function(){ return 5;};
    var num = new Number(5);
    num.x = f.valueOf;

    num.x();                            ------> this should return 5 and it is doing as expected.

     

     

    Now instead of valueOf, if we have toString then we get runtime error

     

    var f = function(){ return 5;};
    var num = new Number(5);
    num.x = f.toString

    num.x();                                ----> this should return 5, but we are getting a runtime exception "function expected".

     

    Well, he was expecting same behavior in both cases which was not happening due to following reason...

     

    In runtime,  Each builtin type has its own function for toString operation. That means there is a function for number (Let’s say JSNumberToString), for Boolean(Let’s say JSBooleanToString) and so on.  These are all internal functions and not exposed.

     

    When you do num.x = f.toString  the function which returns the string representation of a function object (JSFunctionToString ) is assigned to num.x. JSFunctionToString checks whether the object which it is being applied on, is of type function or not? If not then it throws the error you are getting. In above repro code, he was actually calling JSFunctionToString on a number object. JSFunctionToString finds that it is being called upon a Number object and throws the error.

     

    The same logic holds true for valueOf also. But the difference is that the function type doesn’t have their own valueOf. They inherit it from their parent in prototype chain (Object). Since everything derives from Object in Jscript, the same valueOf works for number also.

     

     

  • A tip for improving perf with JScript...

    Most of you must be knowing this but still i find it useful to share...

    "If you are calling a dom method again and again in your website then it is a good idea to cache it to improve performance."

    For example, let's say you are calling a method window.X1.X2.CallFoo() in a loop...

    for (i = 0; I < 10; I ++)
    {
           window.X1.X2.CallFoo()
    }

    If you change above your code to following then you will certainly gain some performance…

     

    cacheFoo = window.X1.X2.CallFoo;

    for (i = 0; I < 10; I ++)
    {
          
    cacheFoo();
    }

     

    Well, so far so good. But how come caching improves the perf/execution time while the same method in IE DOM is being called in both cases.

     

    The answer lies in the binding logic JScript uses. In first case, in each iteration of the loop, JS first binds to window.X1 then X1.X2 and then calls the method in IE DOM. This binding to IE Dom elements/methods/properties has its own cost.

     

    In the second case, binding happens only once, in the very first line where I am caching the method in a local variable. In this case IE creates a new dispatch object for Window.X1.X2.CallFoo which is assigned to cacheFoo. Next time onwards JS can just call the method, it need not bind again.

     

     

  • JScript exceptions not handled/thrown across frames if thrown from a expando method.

    Hope all of you are doing great!

    Today I am going to discuss sort of limitation of Jscript engine which I had hard time debugging. I hope through this post i can save you guys from running into same issue.

    Scenario -
    Let’s say Foo() is defined in one IE frame (Let’s say FR1) and this method just throws an exception. The same frame also has one object (let’s say myObj1) whose one of the properties points to Foo (let’s say myObj1.callFoo = Foo;). 

    Now user calls this method twice from another frame (Let’s say FR2) … 

    1. In first case the function Foo is called directly  - 
      window.top.FR1.Foo();

    1. In the second case object expando is invoked – 
      window.top.FR1. myObj1.callFoo();

    Issue Reported -
    The issue customer has reported is that when method is called in the second frame directly (window.top.FR1.Foo();), exception is thrown in first frame and caught in the second frame but when it is called through the expando (window.top.FR1. myObj1.callFoo();), exception is thrown in first frame but doesn't reach the second frame. Wow!!!

     

     Reason -

    For every frame IE creates a seperate instance of JScript engine. Let's fay for Frame FR1 it creates engine JS1 and for frame2 engine creates JS2.

    1. For the first case (window.top.FR1.Foo();) - Call from JS2 is delegated to IE which call the function object in JS1. Now here is the catch. When any method in JS engine is called by IE, engine sets the caller property to IE. If some exception is thrown during execution and is there is no try-catch handler, JS engine checks this caller property. If property value is set to the IE (or other host) exception is propogated down to IE (host). IE then propogates it further down in the caller chain. Eventually the exception reaches JS2.
       
    2. Second case (window.top.FR1. myObj1.callFoo();) - IE creates a new dispatch object for the object myObj1 (of the first engine), and returns to the second engine. Since second engine has got a dispatch object, it direclty invokes the method. Neither IE is there in the call chain, nor is the caller set to second engine in the first engine. So when exception is thrown, there is no handler available (as parent can't be traced back) and exception is reported unhandled.

     This behavior is “by design" as once the diispatch object is available, script need not delegate the call to IE. It can direclty call that object's methods.

     

     Workaround

    If you are running into the scenario 2 and can't avoid this then here is the simple workaround. Create a wrapper method in FR1 for every such expando and call that method from FR2.

    For example in FR1 add following ...

    function WrapperCallFoo()
    {

         myObj1.callFoo();
    }

    Now in FR2 replace all window.top.FR1. myObj1.callFoo(); with window.top.FR1. WrapperCallFoo();

     

    I also took a look at Eric's blog. Here one of the comments by Dan Shappir points out that when function is directly called, it is actually called in the context of IE and the second time in the context of the global object. What I have written here is just a detailed explanation of what is going on behind the scene.

     

  • Calling VariantClear on a OUT param can lead to security hole !!!

    There was a mail thread going on internally where a security hole was suspected due to VarianltClear() being called inside a method on a out param. Since i am new to COM world, I asked my fellow MSFTian Paul Dempsey that how can it be possible. Here is what he told me...

    When passing into an OUT parameter, since this variable is receiving a value there is no requirement to initialize it.  If the method calls VariantClear on an uninitialized variant, then what happens depends on the exact pattern of bits in that piece of memory. If the vt part is not a valid variant type, nothing happens. If it is 9 (a Unicode TAB character and also VT_DISPATCH), VariantClear calls Release on the pointer in the variant. This will usually be some invalid address and the application crashes, but if an attacker arranges for the right bits to be in the memory that the variant comes from, he can cause code of his choice to run, yielding elevation of privilege if the code is running in elevated mode.

    I though that this information could be useful for COM Beginners so just shared here :).

  • JScript supports SafeArrays of Variants only!!!

    Recently I investigated a bug in Jscript which was reported on Vista. The scenario was working perfectly fine on XP and win2k3 but regressed in Vista. Here is the repro code...

    var strSCID = "{305CA226-D286-468e-B848-2B2E8E697B74} 2";
    var shell = new ActiveXObject("Shell.Application");
    var cpls = shell.Namespace(3).Items();   // 3 is the ID for Control Panel
    var num = cpls.Count;
    while (num)
    {
       var fldrItem = cpls.Item(num-1);  
       WScript.Echo("The cpl " + fldrItem.Name + " belongs to category id " + fldrItem.ExtendedProperty(strSCID));  
       num--;
    }

    The issue was that above JScript code was printing nothing for fldrItem.ExtendedProperty(strSCID) on Vista. Same script was printing correctly on XP/Win2k3. On Debugging I found out that fldrItem.ExtendedProperty was returning a SafeArray on vista while it used to return a variant of type VT_BSTR or VT_I4 on XP/Win2k3. That means it was ExtendedProperty() which actually changed the behavior and regressed the scenario. Job done!

     But still I was wondering why JScript was not able to print the array because to my knowledge, JScript has got a datatype VBArray which is actually nothing but JScript representation of SafeArrays. I decided to debug more and go to the root of the issue. On debugging further I found out that Jscript can interpret SafeArrays only of Variants, i.e. vt of array variant must be set to VT_ARRAY | VT_VARIANT. On Vista ExtendedProperty() was returning SAFEARRAYS of type VT_ARRAY | VT_I4 and unfortunately Jscript doesn't recognizes these type of safearrays.

    Well, you must be thinking that what do I mean JScript doesn't recognize one type of safearrays but not of other type. . What I mean is, if Jscript is passed a SafeArray of type other than VT_ARRAY | VT_VARIANT, then JScript just keeps the reference. None of the JScript operations which can be performed on a normal JScript VBArray Object, can be performed on these objects. JScript can be used to pass these non-variant safearrays from one automation object to another, but JScript itself can’t manipulate them. Hope it makes the thing clear.

     So if you are designing an Automation object (ActiveX object) and want that object to be consumed by JScript, then…

    1. Design it in such a way that it neither takes nor returns a safearray.

    2. Otherwise design it in such a way that it returns safearrays of type VT_ARRAY | VT_VARIANT (But doesn't take a safearray).

    One important point to keep in mind is that SafeArray of type VT_ARRAY | VT_VARIANT can be converted to JScript representation of arrays but JScript arrays can’t be converted back to SafeArrays. This is just not supported at all. So while designing you ActiveXObject, keep in mind that if any of the methods needs a SafeArray as formal parameter than that method can’t be called from JScript.

     To know more about Jscript VBArrays please read Eric Lippert’s excellent blog.

  • For In Loop in JScript

    Hi,

    It's been more than one year since my last post. I will try to be regular now on :).

    BTW, during this period, I have moved to Jscript team and will be sharing my little knowledge on JScript with you all.

    Recently I investigated a bug wherein user complained that for... In loop in JScript doesn't work. It doesn't enumerate through members of an array like the for..each loop of VBScript or C#. Since I am also new to Jscript and was not sure of the for...in behavior I decided to debug the code and here are the results...

    JScript For in loop is different from for-each of VBScript or C#. For each loop of VBScript and C# indeed iterates through the members of an object but Jscript for in loop actually iterates through indexes. What does that mean? Iterating through indexes not members? Well, let's work out an example...

    var arr = new Array(10, 20, 30);

    for (oBinding in arr)

    {

    WScript.Echo(oBinding)

    }

    What do you think should be the output of above code snippet? Shouldn't it be 10, 20, 30?

    If you run above code, then output will be 0, 1, 2, which are actually array indices. If you want to print the members then you need to change above code as following...

    var arr = new Array(10, 20, 30);

    for (oBinding in arr)

    {

    WScript.Echo(arr[oBinding])

    }

    Above code snippet prints what you were expecting, 10, 20, 30. Hmmmm.... then why do i need a for..in loop at all. I can just use a for loop to print the array members like following....

    for (count = 0; count < arr.length; count++)
        WScript.Echo(arr[count]); 

    Correct! But the need of for..in loop arises when you have a sparse array. JScript arrays are sparse arrays, that is, although you can allocate an array with many elements, only the elements that actually contain data exist. This reduces the amount of memory used by the array. Consider following example...

    var arr = new Array();
    arr[10] = 2;
    arr[15] = 4;
    arr[20] = 5;

    for (oBinding in arr)
    {

               WScript.Echo(arr[oBinding])

    }

    In above code array arr has only 3 valid elements though it's size is 20. If you use a for loop to access this array, you will be accessing all 20 elements which is unnecessay waste of CPU time. Instead if you use for...in loop you will just access 3 elements. Huge saving of CPU!!!

    In other words what you can say is that for..in allows you to randomly access the array.

    Same holds true for object properties also. What if you have a Jscript object but you don't know what all properties it holds. Answer is the for…in loop. Just use a for..in loop on that object and get hold of all the properties. Simple!

     

  • J#/C#/VB Express SKU prevent use of MS Word - Issue made us work hard

    Hi all,

    Last week one J# user (Mike Ward of Eurostep) reported that after installing J# express from this link he was not able to work on any Office tools at all. He could install and work on J# express successfully but as soon as he tried to open Word he got following dialog… 

     

    Image Hosted by ImageShack.us

    On canceling it he got …

    J# error

    We were really scared on being reported this issue as this is something which we had never imagined in our remotest thoughts. Visual J# preventing use of MS Word!!!

     

    This issue was good enough to give us sleepless nights so I instantly got in touch with Mike. I asked him about his machine configuration, Office version and many more questions and tried to repro it in our lab but no luck at all. We thought that it was some corner issue and something went wrong during installation. So I requested Mike to Install J# express again (he had uninstalled it as he was not able to use Office tools) and see if he hits it again. To my worst fears, he could hit it againL. But this time he gave us one more clue. He killed Word after getting these dialogs and reopened again. While reopening he got following dialog…

     

    MS Word Yes/No

     

     

    This clue was good enough to lead us to the real reason behind this strange behavior. Actually he had installed a third part addin for word which converts word documents to pdf format.

     

    This addin was reading following registry key while loading …

     

    [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\87B061495C7D6074E830D9B873367CBD\]

    "PackageName”

    "LastUsedSource"

     

    The LastUsedSource value of this key points to the temporary location of vjssetup.msi, which was valid at the time of installation. After installation vjssetup.msi is deleted from that location. So when addin tries to run this file, dialogs reported by Mike pop up.

     

    I wanted to assure that this was J# express issue or not so I…

     

    1.       Installed C# express. Opened word. Got the same dialog. This time addin tried to read C# express installer key from [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\].

    2.       Installed VB express. Opened word. Got the same dialog. This time addin tried to read VB express installer key from [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\].

    3.       Deleted these keys. Opened word. I didn’t get the dialogs. Hurrah! Both express and word worked fine.

     

    We are still investigating this issue and trying to find out that who is buggy here. We or Addin.

    Meanwhile if you also hit this issue then please apply the workaround – Delete the registry keysJ. I will post here the real cause behind this issue once we are done with our investigations, and I will like to use this platform to thank Mike Ward for reporting this issue and keeping extreme patience and helping us to dig it down. Thanks Mike!!!

     

    Have a great coding Experience with our Express SKUS !!!

     

     

  • Bean Style properties in J#

    In Visual Studio 2005 release, J# supports writing properties in Java bean style also. How are they different from the normal .net style properties of J#? Following is the comparison …

    Bean Style Properties                                    

    .Net Style Properties                           

    Declaration of Getter of bean style property must be prefixed with get. E.g. getName

    Declaration of Getter of .net style property must be prefixed with get_. E.g. get_Name()

    Declaration of Setter of .net style property must be prefixed with set. E.g. setName()

    Declaration of Setter of .net style property must be prefixed with set_. E.g. set_Name()

    Bean Style readonly boolean property can have one more prefix ‘is’. E.g isInitialized.

    No equivalent construct here.

    Declaration of Getter & Setter must be applied @beanproperty attribute.

    Declaration of Getter & Setter must be applied @property attribute.

    The case of the first letter in the property name is converted to lower case unless the property is in all caps, as per the camel casing convention applicable to methods in Java. For Example…

    1.      getName/setName will be exposed as name out of the assembly.

    2.      getNaMe/ setNaMe will be exposed as naMe out of the assembly.

    3.      getNAME/ setNAME will be exposed as NAME out of the assembly.

    No change in the casing. Will be shown as it is declared to outside world.

     

     

     

    Syntax of a Bean Style Property in J# - How to Declare it

     

    Here is the declaration for a bean style property in J#...

     

    package JSProperty;

    /**

     * Summary description for Point

     */

    public class Point

    {

    private int x;

     

                /** @beanproperty */

                public int getxValue()

                {

                      return x;

                }

     

                /** @beanproperty */

                public void setxValue(int value)

                {

                      x = value;

                }    

    }

     

    In the above declaration, you can notice...

    1.  Method name for getter (getxValue) starts with get
    2.  Method name for setter (setxValue ) starts with set
    3.  Both methods have      /** @beanproperty */ attribute applied.
    4.  Method name for setter/getter are same except get and set. This is mandatory if you want to declare a read/write property. If you want to declare a read-only or write-only property then you must not specify setter or getter respectively.

     

    Consuming J# declared Bean Properties in C# - No difference from C# declared property - Beauty of .net

     

    If I compile above code into an assembly and refer that assembly in a C# project then I will be able to consume the property in C# syntax, as if the property was written in C# syntax, not typical method like syntax of J#. Following is the C# sample consuming above property...

     

    using System;

    using System.Collections.Generic;

    using System.Text;

    using JSProperty;

    namespace ConsoleApplication1

    {

        class TestProgram

        {

             static void Main(string[] args)

       {

            Point p = new Point();

                  System.Console.WriteLine("Setting property value to 10");

            p.xValue = 10;

                  System.Console.WriteLine("Property has been set to : " +
                                                      p.xValue.ToString());

               

        }

     

        }

    }

     

    Declaring a read-only or write-only bean style property in J#

     

    If you want to declare a read-only or write-only bean style property then you must not specify setter and getter respectively.  So a read-only property will look somewhat like following...

          public class Point

    {

    private int x;

     

                /** @beanproperty */

                      public int getxValue()

                      {

                            return x;

                }

                // please note that no declaration for setter here        

    }

     

     

    Similarly if you want to declare a write only property then you should declare only setter,

       

          public class Point

    {

    private int x;

     

                /** @beanproperty */

                      public void setxValue(int value)

                      {

                            x = value;

                }

               // please note that no declaration for getter here         

    }

     

    /** @beanproperty */ attribute is critical - Few words of caution

     

    In my J# declaration of bean style property if I miss the @beanproperty attribute then J# compiler won't give any error. It will compile fine and will emit the IL for method of the same name. For example if I declare the property as follows...

     

    public class Point

    {

    private int x;

     

                public int getxValue()

                {

                      return x;

                }

     

                /** @beanproperty */

                public void setxValue(int value)

                {

                      x = value;

                }    

    }

     

     

    then J# compiler will generate IL for a method getxValue () and a write-Only property xValue. That means if you refer such an assembly in a C# project then, you will see one method "int getxValue ()" and a write-only property "property int xValue".

     

    I have observed many people scratching their head due to similar mistakes. Either they forget to put the /** @beanproperty */ attribute or they spell it wrongly. If you spell the attribute incorrectly then also compiler will not give any error/warning. Reason is that attributes in J# are written inside /** */ construct and you can write java doc comments/comments also inside the same construct. So in case you spell the attribute incorrectly then J# compiler treats that as a comment/doc comment and doesn't give any warning/error.

     

    Bean Style Property starting with “is”

    To be on par with java beans, J# support writing Boolean bean style read only property starting with “is”. Here is the example giving some insight…

     

    public class Point

    {

          private int x = - 1;

          private int y;

     

          public void SetX( int value)

          {

                x = value;

          }

     

          /** @beanproperty */

          public boolean isValid()

          {

                return x >= 0;

          }

     

     

    }

     

    In above snippet I have declared boolean style property whose name starts with “is”. I can’t pass any other argument in this property declaration and type must always be boolean. If I don’t follow these two rules then J# compiler gives error.

     

    Here is the C# snippet showing consumption of this bean style property…

    class Program

     {      

            static void Main(string[] args)

            {

                ConsoleApplication2.Point point = new
                                ConsoleApplication2.Point();

                bool x = point.valid;

                point.SetX(4);

                x = point.valid;

                int i = 0;

     

                //int s = point.simpleVaLue;

            }

     }

     

    You can notice here that J# compiler has changed the first letter of property name from uppercase to lower case to confirm the java camel casing.

    In the declaration I have declared the name as following…

    public boolean isValid()

    but in my C# code consuming this property, I am accessing it in lower case…

    x = point.valid;

     

    Declaring Indexers using Bean Style Properties

     

    This is similar to declaring indexers using .net style properties. What all you have to do is…

    1. Apply

     /** @attribute System.Reflection.DefaultMember(%propertyname%) */

     

    to your class declaration and replace %propertyname% with the bean property you want to convert into indexer.

    1. In the property declaration (getter, setter) add one more argument of int type which will be used as an array index by outside world. Please make sure that this is the very first argument in both getter/setter declaration.

     

    Following example will make the things clear…

     

    Declaration in J#...

    /** @attribute System.Reflection.DefaultMember("VALUE") */

    public class Point

    {

          private int x;

          private int y;

     

          /** @beanproperty */

          public int getVALUE(int index)

          {

                switch (index)

                {

                      default:

                      case 0:

                            return x;

                      case 1:

                            return y;

                }

          }

     

          /** @beanproperty */

          public void setVALUE(int index, int val)

          {

                switch (index)

                {

                      default:

                      case 0:

                            x = val;

                            break;

                      case 1:

                            y = val;

                            break;

                }

          }

    }

     

    Consumption in C#...

     

    class Program

        {

          

            static void Main(string[] args)

            {

                ConsoleApplication2.Point point = new
                           ConsoleApplication2.Point();

                point[0] = 2;

                point[1] = 3;

                int x = point[0];

                int y = point[1];

            }

     }

     

     

    So far so good :).

     

    I think this is all about properties in J# from my side. If you have any doubts you may like to

    ·         refer my last posts on properties in J#.

    ·         refer this white paper from our Program Manager Pratap Lakshman.

    ·         Or just post a comment here. I will be more than happy replying on them.

     

    Thanks.

     

  • Writing Indexers in J#...

    In my last post I didn't mentioned that in J# also one can write indexers, as you can write them in C#. In C#, there is a unique syntax to write indexers but in J# it is as good as writing any other property. To convert a property into indexer of a class you have to do following things extra...

    • Suppose you want to convert property "Foo" into indexer of your class then you need to apply following attribute to your class…

                @attribute System.Reflection.DefaultMember("Foo")

    • You need to add one extra parameter of int type to the property which is to be used as index.

    Let’s have a look at an example to make the things crystal clear :).

    Following is my indexer written in J#...

    /** @attribute System.Reflection.DefaultMember("Counting")

     */

    public class Program

    {

         

          private String Array[] = { "First", "Second", "Third"};

          /** @property

           */

          public String get_Counting(int index)

          {

                return Array[index];

          }

     

          /** @property

           */

          public void set_Counting(int index, String Value)

          {

                Array[index] = Value;

          }

    }

     

    In the above snippet,

    1. I have declared property “Counting”. To make it an indexer of this class, I have set it the default member of the class by specifying it’s name in the DefaultMember Attribute. Please note following line in the code…

    @attribute System.Reflection.DefaultMember("Counting")

     

    1. I have added one extra int parameter to the property declaration. This parameter is the actual index you specify when you use this indexer. Note following lines in declaration of setter and getter…

    public String get_Counting(int index)

    public void set_Counting(int index, String Value)

     

    Now if you want to consume this indexer in C#, then you are all set to use it like any other indexer declared in C# itself. Following code snippet shows how to use above declared indexer in C#...

     

    class Program

        {

          

            static void Main(string[] args)

            {

    ConsoleApplication2.Program prg = new ConsoleApplication2.Program();

                prg[0] = "HI";

                String x = prg[0];

                int i = 0;

     

            }

      }

     

    Note following lines of code in above snippet…

     

    prg[0] = "HI";

                String x = prg[0];

     

    I declared "Counting" property in J# using J# syntax but I am able to consume it in C# in C# syntax.

    For J# properties i would like to recommend you to read this white paper written by our very own Program Manager Pratap Lakshman.

     

    Thanks.

     

  • Properties in J#...

    J# supports writing properties but syntax is quite different from C#. In C# properties have there own syntax and style but in J#, properties look like a regular method except following differences...

    • A method name representing a property getter must start with get_ and a property setter with set_.      
    • A method representing a property getter/setter must have /** @property */ Attribute applied to it.

    If any of these conditions is not fulfilled then J# compiler will treat the declaration as simple method declaration and will emit the IL(Intermediate Language) for a method only. What does that mean? This means that if you refer an assembly containing such a wrongly declared property, in a C#/VB/any other .net language project, then you will not see a method not the property.

     

    Syntax of a Property in J# - How to Declare a Property

     

    Here is the declaration for a typical property in J#...

     

    package JSProperty;

    /**

     * Summary description for Program

     */

    public class Program

    {

          private String name;

          /** @property

           */

          public String get_Name()

          {

                return name;

          }

     

          /** @property

           */

          public void set_Name(String value)

          {

                name = value;

          }

     

          public static void main(String[] args)

          {

                //

                // TODO: Add code to start application here

                //

          }

    }

     

    In the above declaration, you can notice...

    1.  Method name for getter starts with get_
    2.  Method name for setter starts with set_
    3.  Both methods have      /** @property */ attribute applied.
    4.  Method name for setter/getter are same except get_ and set_. This is mandatory if you want to declare a read/write property. If you want to declare a read-only or write-only property then you must not specify setter and getter respectively.

     

    Consuming J# declared Properties in C# - No difference from C# declared property - Beauty of .net

     

    If I compile above code into an assembly and refer that assembly in a C# project then I will be able to consume the property in C# syntax, as if the property was written in C# syntax, not typical method like syntax of J#. Following is the C# sample consuming above property...

     

    using System;

    using System.Collections.Generic;

    using System.Text;

    using JSProperty;

    namespace ConsoleApplication1

    {

        class TestProgram

        {

            public void ConsumeProperty()

            {

                Program prg = new Program();

                prg.Name = "Jaiprakash";

                String name = prg.Name;

               

            }

        }

    }

     

    Declaring a read-only or write-only property in J#

     

    If you want to declare a read-only or write-only property then you must not specify setter and getter respectively.  So a read-only property will look somewhat like following...

          /** @property

           */

          public void get_Name(String value)

          {

                name = value;

          }

    Similarly if you want to declare a write only property then you should declare only setter,

       

          /** @property

           */

          public void set_Name(String value)

          {

                name = value;

          }

     

    /** @property */ attribute is critical - Few words of caution

     

    In my J# declaration of property if I miss the @property attribute then J# compiler won't give any error. It will compile fine and will emit the IL for method of the same name. For example if I declare the property as follows...

     

                public String get_Name()

          {

                return name;

          }

     

          /** @property

           */

          public void set_Name(String value)

          {

                name = value;

          }

     

    then J# compiler will generate IL for a method get_Name() and a write-Only property Name. That means if you refer such an assembly in a C# project then, you will see one method "String get_Name()" and a write-only property "property String Name".

     

    I have observed many people scratching their head due to same mistake. Either they forget to put the /** @property */ attribute or they spell it wrongly. If you spell the attribute incorrectly then also compiler will not give any error/warning. Reason is that attributes in J# are written inside /** */ construct and you can write java doc comments/comments also inside the same construct. So in case you spell the attribute incorrectly then J# compiler treats that as a comment/doc comment and doesn't give any warning/error.

     

    Consuming C# written properties in J#

    Suppose you have referred a .net assembly, originally written in C#, and you are referring that in a J# project. In J# you can’t access them as you do in C#. In J# a

    get_XXXXX method is exposed for getter of property and a set_XXXXX method is exposed for setter.

     

    For example if you have written following code in C#...

    using System;

    using System.Collections.Generic;

    using System.Text;

     

    namespace CSproperty

    {

        public class CSproperty

        {

            public CSproperty()

            {

            }

            private String address;

            public String Address

            {

                get

                {

                    return address;

                }

                set

                {

                    address = value;

                }

            }

        }

    }

     

    In J# project you can consume it as following snippet shows…

     

    package JSProperty;

     

    /**

     * Summary description for Program

     */

    public class TestProgram

    {

         

         

          public static void main(String[] args)

          {

                CSproperty.CSproperty csProp = new CSproperty.CSproperty();

                csProp.set_Address("Microsoft");

                String address = csProp.get_Address();

          }

    }

     

    Reason Behind this difference from C#

    Obviously we want to make it simple for those who are familiar with J# syntax. We don't want to make them learn a new syntax for something which they are habitual of writing in some particular syntax

    So, this was all about properties in J#. I will recommend having a look at the IL generated by J# compiler for properties. Change the declaration, like remove the attribute or misspell the attribute, build the code and check the IL using ILDasm. It will help you understand the behavior I have described above.

     

    I my next post I will be discussing bean style properties in J#, so stay tuned!!!

  • BadImageFormatException for a J# assembly on 64 Bit machine.

    Hi,
    Today I would like to write about something which left me clueless for hours and really made me work hard to figure the root cause.
    I was building and running a suite on a 64 bit machine. This suite was written in C# and referring few existing dlls written in J#. I had ran same suite with same set of J# dlls referred on a 32 bit machine and everything used to work fine there, but suddenly on the 64 bit machine it stopped working.

    It as compiling fine but while running, it was throwing following exception ...

    System.BadImageFormatException
    Message="Could not load file or assembly JSharp'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format."

    I had no clue that why suddenly it started failing on 64 bit machine while I didn't change anything, neither in my suite code nor in the referred J# assembly :(.
    After spending no of hours I found out the reason. It was behaving erroneously only on 64 bit machine because J# compiler doesn't support 64 bit platform as of now. When one builds J# project, the exe or dll is always marked for 32 bit platform irrespective of the machine it is built on. That means even if I build a J# dll on 64 bit machine, it will be marked as 32 bit dll only.

    So when I refer such a J# dll in C# project and build the C# project on 64 bit machine, C# dll is built for 'Any CPU' platform by default. On 64 bit machine 'Any CPU' maps to 64 bit platform. Now when I run such a C# project which has been built for 'Any CPU' platform and refers a J# dll, BadImageFormatException is thrown because loader tries to load a 32 bit dll in 64 bit process address apace which is obviously going to fail.

    This issue is there not only for J#. You can build a C# or VB .net dll for a 32 bit platform by passing /platform : x86 switch to compiler. Now if you refer such a dll in a C# project, build it on 64 bit machine for 'Any CPU', run it then you will hit same exception. Solution to overcome this situation is that while building your C#/VB .net project on 64 bit, which refers 32 bit C#/J#/VB .net dll, you must specify /platform:x86 switch to compiler.

    Since J# doesn't support 64 bit platform in VS 2005 (J# supports only 32 bit platform in VS 2005), this switch /platform : x86 is not there for J# compiler. If you try specifying it to J# compiler (vjc), it will crib saying invalid switch. J# compiler by default compiles for x86 only.

    So friends, if you ever hit BadImageFormatException, do check the target platform of the assembly. You might also be running into the same problem.


     

  • Here I come...

    Hi Friends,
    This is Jaiprakash, working as SDET in Visual J# team for the last few years. During this stint with J#  I have learnt quite a lot interesting things about different aspects of product development, about .net, about J# and had some real cool experiences. Through this channel I am going to share them with you all.

    I would love to start with something which really confused me when I started working with J# team. In J# access specifier "protected" has special behavior from other .net languages e.g. C#.
    If you write a protected inner class in J#, compile it and refer the assembly in a C# project then your J# class is shown public not protected. Confusing!!!

    So here is the explanation for this special behavior...

    In J# following are the mappings of Access Specifiers to MSIL (Microsoft Intermediate Language - The intermediate language to which your code is compiled in .net) semantics…

    Private in J#  ->  Private in IL
    Public in J#  ->  Public in IL.
    Package in J#    ->   Nothing in IL
    Protected in J#  ->  Public in IL (By default)

    The reason why J# protected doesn’t map to protected in IL is that each access specifier is superset of the other and ‘protected’ is superset of ‘package’ in J#. In J# package specifier means that access is available to classes in the same package and the package can be distributed in more than one assembly. Since ‘Protected’ in J# implies Package also, therefore in addition to obeying the general semantics it must confirm to Package semantics too. Since Package can be distributed across different assemblies, we simulate the required behavior by mapping ‘protected’ in the source code to ‘public’ in IL.

    This is the default behavior in J#. If you want to turn off this behavior then you must compile your source code with securescoping compiler switch (/securescoping[+|-]). This option marks "package" scope as "internal" in meta data.

    If you are compiling in Visual Studio then you can turn on securescoping option from Project Properties pages. Following are the steps to follow...
    1. Right click on Project node in solution explorer.
    2. Click project properties.
    3. Click Build Tab in Project properties designer.
    4. Click Advanced Button.
    5. Check Secure Scoping check box.
    6. Build your project.

    The default behavior is there for the compatibility with Java language and secure scoping option is there to allow user to have consistency with other languages supported by CLR.

    Hmmm…it's getting too lengthy so let’s have a break. Keep visiting as I would be reveling more such confusing but interesting :) stories here.


     

     


© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker