GithubHelp home page GithubHelp logo

nikhilk / scriptsharp Goto Github PK

View Code? Open in Web Editor NEW
660.0 71.0 183.0 11.82 MB

Script# Project - a C# to JavaScript compiler, to power your HTML5 and Node.js web development.

Home Page: http://scriptsharp.com

License: Other

C# 96.52% JavaScript 3.16% PowerShell 0.17% CSS 0.14% Shell 0.02%

scriptsharp's Introduction

Script# Project

Script# is a development tool that generates JavaScript by compiling C# source code. It is especially interesting for scripting-in-the-large scenarios that is commonplace in the current generation of HTML5, node.js and script-based Web applications.

The driving principle behind Script# is that JavaScript is the "assembly language of the Web" ... the idea isn't to dislike JavaScript, but rather appreciate it for its flexibility and ubiquity, while bringing the productivity and familiarity of C# when building large scale (large codebase, large team or project over a longer period) application where stronger tools, more maintainable codebases are of utmost importance. You might have heard of this described as "application scale".

Specifically, Script# lets you leverage the experience of C# (intellisense, build-time error checking, natural language syntax for OOP constructs), the power Visual Studio IDE and standard .NET tools ecosystem (such as msbuild, refactoring, unit testing, static analysis, code visualization, fxcop). Script# brings all this to you without abstracting the runtime environment - you're still authoring plain-old JavaScript and incorporating the best practices and idioms of JavaScript, just with a different set of tools.

You can even use Script# to work against other existing frameworks and APIs such as jQuery, jQuery plugins and Knockout, and can be extended to work against other existing script.

Script# requires .NET 4.0 and Visual Studio 2012. You can also use one of the free Express tools instead such as Visual Studio 2012 Express for Web or Visual Studio 2012 Express for Windows Desktop.

More Information

The following set of links are relevant if you're using Script# and want to learn more or ask questions, or stay up-to-date.

The Script# Wiki contains the following bits of information if you're checking out the repository, are interested in creating a private build, or even better, looking to contribute to the project.

Credits

Script# builds on the excellent Mono.Cecil project. Thanks to Jb Evain.

Thanks to all the contributors who have contributed to Script# over time. Your contributions are welcome, and appreciated. Let me know how you can help - whether its in the form of a feature, a sample, or some evangelizing/spreading the word, or via a suggestion. See the status page in the wiki for roadmap, plans, and some thoughts about possible contributions.

License

Copyright (c) 2012, Script# Project. Script# is licensed under the Apache 2.0 License.

scriptsharp's People

Contributors

andekande avatar aschoenebeck avatar igochkov avatar jamescourtney avatar jimmygilles avatar markstega avatar martinnormark avatar mattclay avatar mattjphillips avatar michaelaird avatar mwe avatar nikhilk avatar prodigysim avatar robitar avatar rsking avatar strygo avatar talshani avatar theoutlander avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scriptsharp's Issues

Assembly-wide ScriptNamespace

Definitely not a big issue, but it would be convenient to not have to use ScriptNamespace on all classes and instead do it once for each namespace.

For example: ScriptNamespace("My.Very.Long.Namespace", "abc");

can't compile when using namespace to reference a static

// this file will not compile.
// (Check that your C# source compiles and that you are not using an unsupported feature.)

using System.Runtime.CompilerServices;

namespace TestNameSpace1
{
    public class Main
    {
        public Main()
        {
            string test = TestNameSpace2.StaticClass.test();
        }
    }

}

namespace TestNameSpace2
{
    public static class StaticClass
    {
        public static string test()
        {
            return "success";
        }

    }
}

IntrinsicProperty crashes the compiler when not in an Imported class

Marking a property as intrinsic, if it isn't in a class that is Imported, crashes the compiler with no error messages.

A simple test case is:

public class Class1
{
    private string m_lastName;

    [IntrinsicProperty]
    public string LastName
    {
        get { return m_lastName; }
        set { m_lastName = value; }
    }
}

When using the command line compiler on this file, it results in a NullReferenceException

Generated string literals could be optimized

String literals are always within single quotes; instead double quotes could be used if the string value itself contains a single quote.

Secondly, both double quotes and single quotes are escaped, instead only one (based on quotes used around the string value) need to be escaped.

Imported class with overloaded methods and check that your source compiles error

When i define two overloaded functions like below in my imported script class (actually its a custom import of jQueryObject)

[Imported, IgnoreNamespace]
public class Query
{
public Query html(string html) { return null; }
public string html() { return null; }
...
}

And use it like
J.Query.select("#test").html("").children().attr("href", "#" + id)......

i get an error "Check that your C# source compiles and that you are not using an unsupported feature."

When i change parameterless method to "Html()" like below it works just fine.

public Query html(string html) { return null; }
[ScriptName("html")]
public string Html() { return null; }

Missing overload on jQuery : Html( JQueryObject)

jQuery allows to set html from another jQuery object:

eg.
var _summaryContent = $('<ul id='summary-ul' class='error'></ul>');

// loop items
_summaryContent.append('<li>'+ item + '</li>');
// end loop

$('#divId").html( _summaryContent);

currently Html does not allow to be called with jQuery object

Namespace issue

I got two classes named Event. The first one is my own wrapper class and the second one is from an imported lib.

I'm getting an error saying: Check that your C# source compiles and that you are not using an unsupported feature.
When I'm trying to use the imported lib like this

imported.lib.Event.AddListener(element, 'click', handler);

Embedding javascript in Script# DLL to ease referencing

I believe I have a way to deal with embedding javascript reasources into Script# script and import libraries, so that the DLL can simply be referenced from another web project, and by calling a single method during Global.asax.Global.Application_Start, the script can be saved to whatever Scripts folder is necessary (this also facilited by some post build steps in the ss project). Not quite perfect, but vastly easier than the current, manual and 'labor intensive' way of moving DLL's and their corresponding .js's around and specifying a hard output directory, also helps keep versions of each together. The problem I'm having is your ScriptAssembly attribute. Script# wont compile with out it, but when a script# DLL is loaded during runtime (when the call from Application_Startup is made to copy the embedded javascript resources), ScriptAssemblyAttribute doesnt exist in System namespace (because compiler is now using the 'real' mscorlib), and an exception is thrown. I understand using ScriptAssemblyAttribute to prevent someone from trying to use a 'real' clr assembly in a script project, but I'd much rather be able to ease referencing like I've described above, than be 'protected' from referencing 'real' assemblies. Can you add an option to NOT check for ScriptAssemblyAttribute? or move that attribute out of your mscorlib?

Javascript best practice pattern for classes

I've just learned about a best practice for javascript classes , to avoid namespace collisions and handling private and public variables and fucntions, and I really like the pattern. I was wondering how I could port it to scriptsharp. The pattern is the following:

(function(myobject,$,undefined) {
   // private variable
   var privateVar = true;
  // public variable
 myobject.publicVar = "some public var";
  // public function
  myobject.doSomething = function() {
        addItem("test");
        additem("another");
  };
  // private function
  function addItem(item) {
      if (item!=undefined) { console.log("adding"); }
  }
} (window.myobject = window.myobject || {} , jQuery ));

I can create the part

 (fucntion (myobject,$,undefined) { 
    ...
} (window.myobject = window.myobject || {} , jQuery ));  

perfectly with the .script file in the properties folder of my project.

public function can be added perfectly when I decorate my class with

[Mixin("myobject")]

and adding a static function.

But static variables are not allowed on Mixins, so I cannot create a private variable or public variable and a private function is translated to

myobject._addItem = function myObjet$additem(item) { ... }

I know this pattern is somehow different from the one scriptsharp now implements, but , it allows for true private variables and functions, not just by convention and by enforcing access through the scriptsharp compiler... because if one writes a class that can be consumed by none scriptsharp code, private variables / functions are still accessible.

I was wondering if you might consider this type of pattern, perhaps by using a special attribute to give the user this option of creating code.

Incorrect use of 'this' in anonymous function.

(Posting the repro here on Github)

I found a situation where the ouput'd anonymous function is not wrapped properly in 0.7.0, leading to incorrect use of 'this'.

Code:

using System;
using System.Web;
using jQueryApi;

namespace ABC
{
    public partial class MyType
    {
        protected jQueryObject InstanceMethod1(string id)
        {
            return null;
        }

        protected void InstanceMethod2()
        {
            jQueryObject jqLabels = jQuery.Select("label[for]");
            jqLabels.Each(delegate(int index, Element element)
            {
                jQueryObject local1 = InstanceMethod1();
            });
        }
    }
}

Output:

Type.registerNamespace('ABC');

////////////////////////////////////////////////////////////////////////////////
// ABC.MyType

ABC.MyType = function ABC_MyType() {
}
ABC.MyType.prototype = {

    instanceMethod1: function ABC_MyType$instanceMethod1(id) {
        return null;
    },

    instanceMethod2: function ABC_MyType$instanceMethod2() {
        var jqLabels = $('label[for]');
        jqLabels.each(function(index, element) {
            var local1 = this.instanceMethod1();
        });
    }
}


ABC.MyType.registerClass('ABC.MyType');

Upgrade from 0.6.3 to 0.7.0.2 causes "Build Failed" with no error information.

After upgrading from 0.6.3.0 to 0.7.2.0 started getting dreaded Build Failed with not errors. In the process project's .js and xml doc files get generated successfully, but DLL does not.

I tried two different approaches with the same outcome:

  1. Upgraded S# solution from 0.6.3.0 to 0.7.0.2.0 by changing mscorlib entry in csproj files, and some projects stopped building with dreaded Build Failed and no error messages, while other projects are OK.
  2. Created a brand new 0.7.0.2 S# project and started adding CS files one by one and building. After adding a complex code file with 1500+ lines of code, started getting build failure. Removing the file makes project build again. The same file built fine in 0.6.3.0.

We are heavily invested in S# with a production project on the line. S# upgrade process was not smooth before, but this one is a show stopper and now we are really concerned. We would appreciate any help with the issue. I can email the project if there is a secure place to place it into.

All the best,
Vlad.

Nothing emitted for abstract properties

If I add an abstract property, the compiler ignores it when generating script, but it does emit null get_ and set_ properties for an interface definition, is there any reason why abstract properties cant be represented in the same way?

For context, I'm looking at the prototype of the generated classes at runtime so I can proxy abstract property accessors with implementations that work with a Knockout observable.

Currently, the only way to get this working is to create an interface and implement it on the type, then sniff the properties on the interface. It's an added burden which almost outweighs the benefit of using normal properties instead of observable delegates (almost).

C# code

namespace Client.Model {
    public interface IModelClass {
        string Prop { get; set; }
    }

    public abstract class ModelClass {
        public abstract string Prop { get; set; }

        public string Foo {
            get {
                return null;
            }
        }
    }
}

Generated Script

////////////////////////////////////////////////////////////////////////////////
// IModelClass

IModelClass = function() { 
};
IModelClass.prototype = {
    get_prop : null,
    set_prop : null
}
IModelClass.registerInterface('IModelClass');


////////////////////////////////////////////////////////////////////////////////
// ModelClass

ModelClass = function ModelClass() {
}
ModelClass.prototype = {

    get_foo: function ModelClass$get_foo() {
        /// <value type="String"></value>
        return null;
    }
}

jQueryEvent.Which

Return type on this property is actually an int in jquery - it is string in script#

unexpected behavior when using static and const classes

In the alert, we are expecting "success", but we are receiving "undefined".

using System;

namespace TestProject
{
    public static class Page
    {
        static Page()
        {
            Class1 c = new Class1();
        }
    }

    public class Class1
    {
        // removing const will make this code succeed.
        const string test = "success";

        public Class1()
        {
            //  expected 'success', but received 'undefined'
            Script.Alert(test);
        }
    }
}

This is the output produced, you can see the const value is being set at the bottom of the file.

//! delme.debug.js
//

(function() {

Type.registerNamespace('TestProject');

////////////////////////////////////////////////////////////////////////////////
// TestProject.Page

TestProject.Page = function TestProject_Page() {
}


////////////////////////////////////////////////////////////////////////////////
// TestProject.Class1

TestProject.Class1 = function TestProject_Class1() {
    /// <field name="_test" type="String" static="true">
    /// </field>
    alert(TestProject.Class1._test);
}


TestProject.Page.registerClass('TestProject.Page');
TestProject.Class1.registerClass('TestProject.Class1');
(function () {
    var c = new TestProject.Class1();
})();
TestProject.Class1._test = 'success';
})();

//! This script was generated using Script# v0.7.0.0

Also, it seems to be reporting v.0.7.0.0, but the mscorlib.js has this version: '0.7.1.0'

invoking AjaxErrorCallback<object> does not compile with 7.0.2

in some class, i have a function

public void postData(string url, object data, AjaxRequestCallback<object> successCallback, AjaxErrorCallback<object>    errorCallback)
{
...
        if (!Script.IsNullOrUndefined(errorCallback))
              errorCallback(req, textStatus, error); // this line does compile with 7.0.0 but not with 7.0.2
}

The line which tries to invoke the errorCallback gives a compiler error:
Check that your c# source compiles and that you are not using an unsupported feature.
It was compiling just fine with verison 7.0.0.

P.S. apparently the mscorlib and other dll's still have version number 7.0.0, while mscorlib.js has version 7.0.2. This is a little bit confusing, because until I looked at mscorlib.js I was thinking the scriptsharp.zip on your site was still containing setup for 7.0.0.
P.S.1 maybe it would be usefull to leave older version of scriptsharp downloadable on your site, so we can revert to an older version if necessary (I unfortunately didn't make a copy of the zip file, so I am left with an project which won't compile anymore)

ScriptSharp 0.7.1 and AjaxRequestCallback<object> compilation fails

I'm attempting to upgrade my version of ScriptSharp from 0.6.2 to 0.7.1 to take advantage of the new generics feature. The last issue I have come across that I don't know how to solve is this: when making an Ajax call, the compiler fails with the message "Check that your C# source compiles and that you are not using an unsupported feature".

Here's the code:

jQuery.Ajax(
        new jQueryAjaxOptions(
            "url", url,
            "type", "GET",
            "dataType", "html",
            "contentType", "application/json",
            "processData", false,
            "success", (AjaxRequestCallback<object>)delegate(object result, string textData, jQueryXmlHttpRequest<object> XMLHttpRequest)
            {
                container.Html(XMLHttpRequest.ResponseText);

                Type.InvokeMethod(null, "ajaxUnBlock", null);
            },
            "error", (AjaxErrorCallback<object>)delegate(jQueryXmlHttpRequest<object> request, string textData, Exception e)
            {
                //Debug.TraceDump(XMLHttpRequest);
            }
        )
    );

I know it's the delegates which are causing this. If I was to instead populate the properties of jQueryAjaxOptions (as opposed to providing a dictionary of key/values) then when I double-click the error in the error window it points me to the line which specifies the success delegate.

I seem to be able to work around it by creating a method instead of using an anonymous delegate and the compiler error goes away, but I would like to avoid going down that road if at all possible as I have a large amount of code which would have to be converted in this way.

OR... Making the function which contains this anonymous delegate static fixes the issue. While researching this issue I found a closed issue on Github (#22) which seems related - the only thing I'm unsure of now is whether this behaviour is intended or not.

Knockout api support

Is there a possiblity that you will implement also bindings and support for knockout.js?

Using namespace alias causes compile errorr

In v0.7.0.0, Get the error "Check that your C# source compiles and that you are not using an usupported feature" at line new'ing Bar.B;

using Bar = Foo.Bar;
using B = Foo.Bar.B;

namespace ns
{
class A
{
public void SomeMeth()
{
// this works
Foo.Bar.B b1 = new Foo.Bar.B();
// this works
B b2 = new B();
// this doesn't work
Bar.B b = new Bar.B();
}
}
}

last pdf for v0.5.5.0 says on page 34:

In addition there are a known set of limitations in the current implementation that will hopefully be supported in future builds:

๏‚ท You cannot specify namespaced-qualified type names either. As a workaround you can use aliases (eg. using Foo = SomeNamespace.SomeType;)

But I could specify namespace-qualified..

Generic overloads / JS global functions

Seems to missing support for the following global JavaScript functions:
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
isFinite()
isNaN()
unescape()

numeric .parse() functions could really use overloads for chars not just strings.

'as' casting breaks on System.Html.Elements

C#:
// Works
CheckBoxElement element1 = (CheckBoxElement)jQuery.Select("input[type='checkbox']").First().Context;
//Throws JavaScript error.
CheckBoxElement element2 = jQuery.Select("input[type='checkbox']").First().Context as CheckBoxElement;

Javascript:
// Works
var element1 = $("input[type='checkbox']").first().context;
// Generates undefined exception for CheckBoxElement
var element2 = Type.safeCast($("input[type='checkbox']").first().context, CheckBoxElement);

Script# compilation symbol.

This is really very minor. I think it would it help in code sharing (both cross-"platform" and cross-team) if there were an official compilation symbol defined for Script# csproj's, for instance SCRIPT_SHARP. It appears that the csproj template already defines CODE_ANALYSIS by default, so my proposal would be to change the default to CODE_ANALYSIS;SCRIPT_SHARP or similar.

Help improving Script# to support more C# Language features

Nikhik,

I've tried contacting you via blog and email, but have heard no response. I think Script# is great, and would like to help improve it. I have experience writing compilers, and have perused Script#'s via Reflector. I have other ideas that could also ease using Script# libraries from other projects, and not require specifying a script output directory everytime.

Why wont you let me help you?

-Paul

object initializers not supported?

Scriptsharp compiler does not support object initializers, is this planned in the future?
Basically, it would be very usefull for initializing jquery plugins the way it's done in javascript. As far as i can see (correct me if am wrong), when you define a class for custom options, it can only be inialized using the constructor
(params object[] nameValuePairs) to get code like in javascript. But of course, one looses the intellisense which could be used if object initlializers would be available. This kind of limits the use of these option classes only inside plugins, not when calling them.

Multi-dimensional arrays are broken in referring projects

I Have new Solution with two project
One is "IncludedProject" has one class

namespace IncludedProject
{
    public class Class1
    {
        public int[][] Member;
    }
}

which compiles fine.

the other one ("Script" project) also has one class

namespace Script
{

    public class Class1
    {
    }
}

Script has a "project reference" to IncludedProject

and it doesn't compile with the following error

Error   1   Unable to resolve referenced type 'System.Int32[]'. Make sure all needed assemblies have been explicitly referenced.    C:\Program Files (x86)\ScriptSharp\v1.0\ScriptSharp.targets 33  5   Script

this happens with any type i checked instead of int

Suggestion: name change for template for Script# class template

Would it be possible to rename the Class template to "Script# Class"...

Once in I while, I find myself adding a Script# class to a non Script project by accident.
This has the annoying effect that it adds Script#'s dll's to the project.
If the name would be 'Script# class' I would immediately see the difference and I guess it would be just a small change.

Generic class with a generic action wont compile

If i try and create a class with a generic attribute and then add a field with a generic Action that uses's the class' generic attribute
the project does not compile and gives no error message, here's an example of what wont compile

public class GenericTest
{
Action MyAction;
}

thanks
-Kris

WebAppPartitioning limitations

Currently we're using ScriptSharp in a rather large enterprise project, and we're making use of the WebAppPartitioning flag in the project file to cause ScriptSharp to generate one .js file per root folder from inside our project.

However, when we come to use code across folders the compiler complains that we're using an unsupported feature and will not build. Instead we should be putting such code into the Shared folder so that the output is copied into each partitioned file.

I think I understand why this is done - the risk is that code would be split across two js files and there is more room for error.

If the above is correct and there isn't a technical limitation from the compiler's perspective as to why it prevents us from using partitioning in this way, is there a way for you to allow us to opt-in to prevent this check from happening (such as another project file setting), and leave it up to the responsibility of the developer to make sure all relevant code files are included on the web page?

As it stands, when we use S# to author several different frameworks within the same project, but some other code depends on one of these frameworks, we can't code against it because of the above limitation.

Web Partitioning is excellent, but in order to make full use of it we really need to be able to code against types which exist in different root folders.

If this is not possible, could you briefly explain how the bigger projects which use S# overcame this limitation? It seems likely to me that they would have already come across this.

Thanks

Interop customization

It would be a really nice interop feature to allow the customization of interop through something like a [CustomInteropAttribute].

Problem Description

Dojo

For a Dojo Script# wrapper, I would want to be able to transform the C# code

widget.Disabled = true;
bool d = widget.Disabled;

to

widget.set('disabled', true)
var d = widget.get('disabled');

KnockoutJS

To use Script# with Knockout view models, a nice way to handle observables would be to transform

model.PropertyName = "PropertyValue";
string pn = model.PropertyName;

to

model.propertyName('PropertyValue');
var pn = model.propertyName();

JQuery

(This is not as important as the other ones since there is already a perfecly valid option, and one could argue that it is not even a good idea. However, I'm doing code generation and currently I have to handle JQuery events differently from all other events because of the different syntax, so it would definitely help me).
JQuery event subscription could be made more .net-like by allowing the transform of

elem.Click += myClickHandler;
elem.Click -= myClickHandler;

to

elem.click(myClickHandler);
elem.unbind('click', myClickHandler);

Proposed feature

The [CustomInteropAttribute] could be used like this:

[Imported, Record]
public class MyKoJSViewModel {
    public string MyProperty {
        [CustomInterop("{this}.myProperty()")]
        get { return null; }
        [CustomInterop("{this}.myProperty({value})", Chainable = false)]
        set {}
    }

    [CustomInterop("{this}.myProperty.subscribe({value})")]
    public IDisposable OnMyPropertyChanged(Action<string> handler) {}
}

[Imported, Record]
public class MyDojoWidget {
    public string MyProperty {
        [CustomInterop("{this}.get('myProperty')")]
        get { return null; }
        [CustomInterop("{this}.set('myProperty', {value})", Chainable = false)]
        set {}
    }
}

The Chainable property would be required because the setter does not return a value, so

string x = object.MyProperty = "x"

would not work out of the box, and preferrably the compiler should either rewrite this, or issue an error.

Even better would be to be able to write a plugin for the code generation process so I could write a plugin that would enable me to say:

[Imported, Record]
public class MyKoJSViewModel {
    [KoJSObservable]
    public string MyProperty { get { return null; } set {} }

    [KoJSSubscription("MyProperty")]
    public IDisposable OnMyPropertyChanged(Action<string> handler) {}
}

[Imported]
public class MyDojoWidget {
    [DojoProperty]
    public string MyProperty { get { return null; } set {} }
}

or even

[Imported, Record, KoJSViewModel]
public class MyKoJSViewModel {
    public string MyProperty { get { return null; } set {} }
    public IDisposable OnMyPropertyChanged(Action<string> handler) {}
}

Culture not modifiable

It would be nice to be able (as it was in 0.5.1 version) to change the current culture.
This way we can use different locales on the same web site, and be able to modify them on the fly (for example when visitor decides to go to French pages instead of English).

This is because propery Culture.CurrentCulture is read-only. Is it possible to modify Current Culture in some other way, except explicitly mentioning the culture I want to use in a specific place? This is quite problematic in our case since we depend on using active culture.

jQueryAjaxOptions - incorrect mapping of JsonpCallback to jsonp

In code you have jsonpCallback mapped to jsonp, but jsonp and jsonpCallback are different, see http://api.jquery.com/jQuery.ajax/

jsonp String

Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }

jsonpCallback String, Function

Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

Missing regex overrides for string replace

Shouldn't be to much work to add them in:

string Replace(RegularExpression, string)
string Replace(RegularExpression, Func<string, string>)

Without them you have to use Type.InvokeMethod, which gets ugly if you want to use a replacement function as you have to assign it to a temporary variable first.

ss.loader.registerScript includes "core" and other assembly referred in that project

After migrating from 0.6.3 to 0.7.1.0, the generated javascript code includes [core] in the registerScript function call. It also includes some other assemblies that are referred in that project. Below is the code generated in two seperate js files

ss.loader.registerScript('TouchMini', [core], executeScript);

ss.loader.registerScript('Framework.Mobile.Touch', [core,Framework,TouchMini], executeScript);

While executing the page in browser I get the below exception
Uncaught ReferenceError: core is not defined

Comparing with null behaviour changed in 0.7.1

ScriptSharp was compiling if (obj == null) and if (obj != null) statements to same expressions in javascript (and i think it was correct) but now it produces (!obj) and (!!obj). If obj has some falsey value like 0, these comparisons may no longer mean what we understand comparing with null should mean in C# (it should give true if obj is undefined or null). People like me have lots of code depending on this check. It may break existing code badly. Please introduce something like Script.IsFalsey, Script.IsNotFalsey etc for those who wants to use this new behaviour and keep old one consistent.

PreserveName inconsistency in debug script

It seems that PreserveName doesn't get applied to fields in debug builds, it should be consistent otherwise you cant really use it as intended.

With the following class in C#:

public class MyClass {
    public string Property {
        get {
            return property;
        }
    }

    [PreserveName]
    private string property;
}

I get this output in debug builds, notice the private field is named "_property" with an underscore

o.MyClass = function o_MyClass() {
}
o.MyClass.prototype = {

    get_property: function o_MyClass$get_property() {
        return this._property;
    },

    _property: null
}

And I get this in release builds, now the field has the intended name of "property"

o.MyClass=function(){}
o.MyClass.prototype={get_property:function(){return this.property;},property:null}

Ability to embed text resources.

This is related to another user's question: http://stackoverflow.com/questions/5857470/clean-way-to-include-html-in-script-projects, and useful for my own code: https://github.com/duckmaestro/Sharp-UI.

For the single-page apps I build, I find it it tedious and error-prone to write scripts that are not tightly coupled with the CSS and HTML that they target. Whether it's dealing with difficult to tame browser cache behavior, or just not having a great encapsulation model for building out complex UIs, I decided to replicate something like the Web User Control model, where "controls" can declaratively instantiate other "controls", where ID'd elements are bound to correspondly-named fields, and, taking it a step further, where locally targetted CSS rules are declared alongside your control's HTML, rather than in a .css file in a completely separate area of your codebase. The "web user control" (WUC) sort of paradigm that I've mimicked has so far given me a lot of mileage and I find it immensely useful for the above stated goals/reasons. It is also useful because I can compile an entire "app" or area into a single JS file, for a single download (faster), and guarenteed consistent HTML/CSS/JS(CS) (fewer reported one-time "bugs" from customers).

At this moment, to get HTML in the Script# output, I use a file naming convention of .html and .html.cs, and compile both files as C#. Both declare the same partial class, and derive from a base class that knows how to locate the HTML string constant. This works well enough except that I must use single-quotes, there is some ugly C# code to maintain at the top and bottom of my HTML files, and there are some other minor limitations as well.

There is potentially a greater solution that could be developed as part of Script# officially (a WUC-like paradigm with designer files etc), though I suspect this strays too far from Script#'s mission and becomes too specialized. So as for the here and now, it'd be great (for in general too) if text resouces could be "embedded" into the JS file for retrieval at run-time. This would allow my HTML files to use the full range of syntax, and avoid some of the other limitations associated with the current HTML as CS build trick.

Crash in ssc.exe when using partial classes.

I have a (close to) minimal example capable of producing a crash in ssc.exe, and a workaround.

Crash:

Script# Compiler v0.7.0.0 (C# to JavaScript compiler)
Written by Nikhil Kothari.
More information at http://projects.nikhilk.net/ScriptSharp.


Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
   at ScriptSharp.Compiler.MetadataBuilder.BuildTypeInheritance(ClassSymbol clas
sSymbol)
   at ScriptSharp.Compiler.MetadataBuilder.BuildMetadata(ParseNodeList compilati
onUnits, SymbolSet symbols, ResourceSet resources, CompilerOptions options)
   at ScriptSharp.ScriptCompiler.BuildMetadata()
   at ScriptSharp.ScriptCompiler.Compile(CompilerOptions options)
   at ScriptSharp.ScriptCompilerApplication.Execute(String[] args)
   at ScriptSharp.Application.Main(String[] args)

Input (command line):

C:\Program Files\ScriptSharp\v1.0>ssc /debug /ref:.\Framework\mscorlib.dll /ref:.\Framework\Script.jQuery.dll ref:.\Framework\Script.web.dll /out:.\SomeScript.js c:\projects\Repros\AssemblyInfo.cs c:\Projects\Repros\BaseClass.cs c:\Projects\Repros\Partial1.cs c:\Projects\Repros\Partial2.cs

Input (files):

AssemblyInfo.cs

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: ScriptAssembly("SomeScript")]

BaseClass.cs

using System;

namespace ABC
{
    public class MyBaseClass
    {
        public MyBaseClass()
        {

        }
    }
}

Partial1.cs

using System;

namespace XYZ
{
    public partial class MyClass
    {
        public string _someField;
    }
}

Partial2.cs

using System;
using ABC;

namespace XYZ
{
    public partial class MyClass : MyBaseClass
    {
        public MyClass()
        {

        }
    }
}

Workaround:

Change the input order so that Partial2.cs comes before Partial1.cs. Of note, Partial1 lacks the base class reference while Partial2 specifies the base class. The workaround if using a csproj is to edit the order the < compile > elements so that Partial2.cs comes before Partial1.cs.

C:\Program Files\ScriptSharp\v1.0>ssc /debug /ref:.\Framework\mscorlib.dll /ref:.\Framework\Script.jQuery.dll ref:.\Framework\Script.web.dll /out:.\SomeScript.js c:\projects\Repros\AssemblyInfo.cs c:\Projects\Repros\BaseClass.cs c:\Projects\Repros\Partial2.cs c:\Projects\Repros\Partial1.cs

Method overriding may fail when using ScriptName attribute.

I've found a case where overriding a method doesn't work as expected:

    public class MyBase
    {
        [ScriptName("hi")]
        public virtual String Hello
        {
            get { return "Hello from base."; }
        }

        public void CallHello()
        {
            Script.Alert(Hello);
        }
    }

    public class MyDerived : MyBase
    {
        public override string Hello
        {
            get
            {
                return "Hello from derived.";
            }
        }
    }

Running this as:

            MyDerived derived = new MyDerived();
            derived.CallHello();

produces an alert from the base class instead. It's caused by the ScriptName attribute. Removing the attribute resolves the issue. Also applying the same ScriptName attribute to the derived class fixes the issue as well.

ScriptSkip has no effect on methods

I am trying to use Script# with KnockoutJS, and so when my properties (actually public fields, due to IntrinsicProperty limitations) are used they need to be used as functions in JavaScript. I have this working with the following code:

[PreserveCase]
[ScriptName("NameFirst")]
public ObservableString _NameFirst;

[ScriptSkip]
[PreserveCase]
public string NameFirst()
{
    return null;
}

[AlternateSignature]
[PreserveCase]
public extern void NameFirst(string value);

So as you can see, I have public fields that are prefixed with an underscore, but told to render without. This works fine, and since the fields are only referenced once, when setting up the Knockout object, its a small price to pay. I then have methods for getting and setting the values from KnockOut, which work well too. From the consumer side of this class, everything is fine.

The problem is that when this class is generated as JavaScript, the ScriptSkip attribute is ignored, and an empty NameLast function is output. I want to prevent this function from being output. I can't use the Imported attribute since that can only go at class level. I can't make both methods extern (which is what they really are) because Script# requires at least one concrete method.

Is this what the ScriptSkip attribute is supposed to do? Is there another way to get Script# to ignore certain methods?

The only workaround at the moment is to define the methods first, then define the fields, which means the generated JavaScript at least works, but it still has a lot of unnecessary generated code.

jQueryObject is missing overloads on replaceWith

I've seen other issues relating to missing overloads for related frameworks and so I'd thought I'd report another one.

Would it be possible to create 2 overloads on jQueryObject.ReplaceWith() to accept (as well as a string):

  • a normal Element
  • another jQueryObject

This is supported by jQuery since v1.2 (as specified at http://api.jquery.com/replaceWith ) and would be very useful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.