Script#: C# to Javascript Converter

Have you heard about Script#? I heard about this toolkit last week even Nikhil started this project last year. I knew that there is a Java-to-Javascript converter called GWT (Google Web Toolkit) in Java World since long time back and I thought that it might be good if we, the C# developers, also have that kinda tools for ASP.NET web development. Now, the dream come true. Nikhil created Script# project that can convert the C# code to Javascript. I think it is pretty interesting (and strange ) tool and I wonder how Script# will convert the C# code to Javascript. Anyway, I started learning about Script# on last Friday. I’m gonna share what I have learnt about it so far. If you are already familiar with this tool, please share your thoughts about this tool. Thanks.

Introduction

Script# is a compiler that generate the Javascript instead of MSIL (Microsoft Intermediate Language) from C# sourcecode. Like GWT (Google Web Toolkit) that can convert the Java code to browser-compliant JavaScript and HTML, Script# is able to convert the C# codes to Javascript (either human-readable format or compact one). It is the best tool for those who hate to write the Javascript in HTML view.

Sourcecode Download : SSharp.zip

Example 1 : Getting Started with Script#

  • Download the ScriptSharp.zip from this link.
  • Extract it and double-click ScriptSharp.msi to install the Script# (You should note that Script# is currently available for Microsoft Visual Studio 2005. If you wanna use Script# with Visual Studio 2008, please check-out this post.)
  • Launch the Microsoft Visual Studio 2005 IDE and let’s create very sample Script# project
    Note: I recommended you to run the VS 2005 IDE as an administrator if you are using Windows Vista series.

  • Click “Script#-Enabled Web site” Project Template from “New Web Site” dialog (File>New>Web Site)
  • We will create one button named “clickMeButton” and the div called “greetingDIV” within
    tag.
    <div>
    <input type="button"  id="clickmeButton" value= "Click Me" />
    <br />
    <br />
    <div id="greetingDIV" class="divbox">
    Hello buddy!!
    </div>
    </div>
    

  • Go to the design-view and right-click on “Scriptlet” control as picture belowScript# - Scriptlet Control
  • Select “Edit C# Code” on content menu.
  • Paste the following code in Scriptlet Editor
    using System.DHTML;
    using ScriptFX;
    using ScriptFX.UI;public class MyScriptlet : IDisposable {private DOMEventHandler _clickHandler;
    
    private MyScriptlet(ScriptletArguments arguments) {
    _clickHandler = new DOMEventHandler(OnClickMeButton_Click);
    
    DOMElement clickMeButton = Document.GetElementById("clickmeButton");
    clickMeButton.AttachEvent("onclick", _clickHandler);
    }
    
    public static void Main(ScriptletArguments arguments) {
    MyScriptlet scriptlet = new MyScriptlet(arguments);
    
    }
    
    public void Dispose() {
    if (_clickHandler != null) {
    DOMElement okButton = Document.GetElementById("clickmeButton");
    okButton.DetachEvent("onclick", _clickHandler);
    _clickHandler = null;
    }
    }
    
    private void OnClickMeButton_Click() {
    DOMElement divGreeting = Document.GetElementById("greetingDIV");
    divGreeting.Style.Display = "block";
    }
    }
    

    Script# - Scriptlet Editor

  • Click “Save and Close” on Scriptlet Editor
  • Build the web application and Press “F5” to run the application
  • (There is one button on the page.) Click this button.
  • “Hello Buddy!” message will be shown as picture below.Script# - Example 1

That’s.. You just created one script#-enabled webpage. Do you want to know what code Script# generated from your C# code? It’s easy. Just go to “View Source” and you will see the following script which is generated by Script#.

<script type="text/javascript">
//<!&#91;CDATA&#91;
window.main = function main() {
Type.createNamespace('Scriptlet');

////////////////////////////////////////////////////////////////////////////////
// Scriptlet.MyScriptlet

Scriptlet.MyScriptlet = function Scriptlet_MyScriptlet(arguments) {
this._clickHandler = Delegate.create(this, this._onClickMeButton_Click);
var clickMeButton = $('clickmeButton');
clickMeButton.attachEvent('onclick', this._clickHandler);
}
Scriptlet.MyScriptlet.main = function Scriptlet_MyScriptlet$main(arguments) {
var scriptlet = new Scriptlet.MyScriptlet(arguments);
}
Scriptlet.MyScriptlet.prototype = {
_clickHandler: null,

dispose: function Scriptlet_MyScriptlet$dispose() {
if (this._clickHandler) {
var okButton = $('clickmeButton');
okButton.detachEvent('onclick', this._clickHandler);
this._clickHandler = null;
}
},

_onClickMeButton_Click: function Scriptlet_MyScriptlet$_onClickMeButton_Click() {
var divGreeting = $('greetingDIV');
divGreeting.style.display = 'block';
}
}

Scriptlet.MyScriptlet.createClass('Scriptlet.MyScriptlet', null, IDisposable);

// ---- Do not remove this footer ----
// Generated using Script# v0.4.2.0 (http://projects.nikhilk.net)
// -----------------------------------

ScriptFX.Application.current.run(Scriptlet.MyScriptlet);
}
ScriptHost.initialize(&#91;
'App_Scripts/ssfx.Core.js',
'App_Scripts/ssfx.UI.Forms.js'
&#93;);
//&#93;&#93;>
</script>

Don’t you think that the generated Javascript code looks so similar to your C# code that you wrote in Scriptlet Editor? Yes. This is one of the advantages of using Script#. It can generate the human-readable Javascript that has the same structure as your C# code. If you are not sure how to write the object-oriented code in Javascript, you can just write the code in C# with the rich features such as IntelliSense, refactoring, compile-time and let Script# convert the C# code to the object-oriented Javascript code.

Note: The sample is already attached in this post. Please check-out “Example1.aspx” in zip file.

Okay. We’ve just done one sample with Script#. As the project is in very early stage, I notice that there are a few weak points and bugs in that project while I’m learning. And also, I’m kinda agreed with Dimitri Glazkov regarding on Script# project. (Check-out his post here.) Anyway, let’s learn more about Script# and we’ll see whether we should use it in real project or not.

Example 2 : Script# Ajax

  • Create the another Script#-enabled project
  • Add the “Generic Handler” to your project and name it “ExampleWebHandler.ashx”
  • Paste the following code in “ProcessRequest (HttpContext context)” function.
    context.Response.ContentType = "text/xml";
    context.Response.Write("Hi " + HttpUtility.HtmlEncode(context.Request.QueryString["name"]) + "!"); 

    Note: What this code does is that write the “Hi” after appending the name that came as a parameter in response.

  • Add one textbox to accept the user inputs, one button to invoke the server-side script and the div for displaying the result
    <div>
    Please Enter your name : &nbsp;&nbsp;
    <input type="text" id="nameTextBox" /> &nbsp;&nbsp;
    <input type="button" id="sayHiButton" value="Say Hi!!"/> <br /><br />
    <div id="result">
    </div>
    </div>
    
  • Add the argument to your scriptlet control. (Right-click on Scriptlet control and select “Edit” Arguments. then, Add one member (Name: name and Value: ExampleWebHandler.ashx?name={0}))

    Edit Arguments - ScriptletArgument Collection Editor

  • then, Click “OK” to close the “ScriptletArgument Collection Editor”
  • Paste the following code in “Scriptlet Editor”
    using System;
    using System.DHTML;
    using ScriptFX;
    using ScriptFX.UI;
    using ScriptFX.Net;
    
    public class MyScriptlet : IDisposable {
    
    private string _urlName;
    private DOMEventHandler _clickHandler;
    private XMLHttpRequest _request;
    DOMElement resultDIV = null;
    
    public static void Main(ScriptletArguments arguments) {
    MyScriptlet scriptlet = new MyScriptlet(arguments);
    }
    
    public void Dispose() {
    if (_clickHandler != null) {
    DOMElement okButton = Document.GetElementById("sayHiButton");
    okButton.DetachEvent("onclick", _clickHandler);
    _clickHandler = null;
    }
    if (_request != null) {
    _request.Onreadystatechange = (Callback)Delegate.Null;
    _request.Abort();
    _request = null;
    }
    }
    
    private MyScriptlet(ScriptletArguments arguments) {
    _urlName = arguments.name;
    
    _clickHandler = new DOMEventHandler(OnSayHiButton_Click);
    
    DOMElement clickMeButton = Document.GetElementById("sayHiButton");
    clickMeButton.AttachEvent("onclick", _clickHandler);
    }
    
    private void OnSayHiButton_Click() {
    InputElement nameTextBox = (InputElement)Document.GetElementById("nameTextBox");
    resultDIV = Document.GetElementById("result");
    resultDIV.Style.Display = "block";
    
    _request = new XMLHttpRequest();
    _request.Onreadystatechange = this.OnRequestComplete;
    _request.Open("GET", String.Format(_urlName, nameTextBox.Value.Escape()), /* async */ true);
    _request.Send(null);
    }
    
    private void OnRequestComplete() {
    if (_request.ReadyState == 4) {
    //if (_request.Status == 200) {
    _request.Onreadystatechange = (Callback)Delegate.Null;
    if (resultDIV != null) {
    resultDIV.ClassName ="divbox";
    resultDIV.InnerHTML = _request.ResponseText;
    }
    _request = null;
    // }
    }
    else {
    if (resultDIV != null) resultDIV.InnerHTML = @"<img src=""./images/indicator_technorati.gif"">";
    }
    }
    }
    

    Note: I assumed that you already have some ideas about Ajax before reading this article.

  • Build the application and run it. (You will see one textbox and one button as you have added on the page.)
  • Type the name you like
  • Click “Say Hi!” button. (You will see the result as below with the name that you enter.)

This demo is very sample that shows the way how to communicate between Script# code and the Server-side code. You can probably extends the web handler to get the more features as you need for your Script#-enabled application.

Debugging the Script#-enabled application

For IE Users, Go to “Debug->Windows->Script Explorer” or Press “Ctl+Alt+N” while you are running the project. You will see the list of script files that are included in page. Select the script file that you wanna debug and set the breakpoint. You know how to debug the Javascript with Visual Studio 2005, right?

For Firefox Users, Firebug is the best tool for debugging the Javascript.

Yeah. It is so sad to say that you are not able to debug the C# code that you wrote. Instead, you will be debugging the Javascript code which is generated by Script# compiler.. It makes you feel like debugging the MSIL code after writing the C# in IDE even the generated code is so much like the C# code that you wrote and human-readable but it is by-design so we can do nothing.

Conclusion

I’m gonna stop learning the Script# project for today. I’ll read about building the Script# library and Vista Sidebar Gadget and will post them in my blog. For the time being, I do have a few disappointments in using Script#. However, I will look more information about this project and I will share the conclusion with you.. If you are also learning this project like me, please let me know. We can probably discuss more about this project.. Thanks…

More Information about Script# ~

How to protect the image from being copied?

Well, it is so sad to say that there is no way to protect the images from being copied until the time of writing this post. You may probably tell me that you found a lot of “Image Protection” tools on web. Yeah. I know. I did even tried some of them once. Those tools make people difficult to copy the images from your website. but there are always some sort of hecks for copying images. No matter what tools or technologies you use.

I will tell some attempts that people tried to achieve this goal and the reason why those attempts were failed.

#1. Disabling “Right Click” on webpage by using Javascript.

This is very very old trick and it’s totally useless. Don’t forget “Save As” in File menu. Plus, there are a lot of DOM manipulators (eg: Firebug) to track the path of images.

#2. Adding new transparent image over the actual image

I found some sites (including flickr) that are using this technique to protect their images from being copied. It works for normal users who only knows “Right Click” and “Save Image As”. You can still check the source to get the correct path of actual image that you want. If you are familiar with firebug, you can easily delete the transparent image that you don’t want on the fly.

#3. Using third-part tools for image protection

If you do googling about this a lit bit, you will get a ton of tools advertising that those tools will help you to protect your image from being copied (some even said that those tools are able to protect HTML code too.) Don’t even never spend your money on those tools. I mean it. As I said above, I tried already. I know those tools are not good enough since they have their own limitations. So, don’t waste your money on it.

This fact applied for code protection tool also. Those tools are going to encrypt your webpage and will add a lot of whitespace in your actual source. So, if you check the “View Source” a lit in your browser, you will see plain text or some text you write instead of HTML code. but don’t forget to scroll a lit bit.. You will see goddammed things.. and those tools will eat your bandwidth and it made your visitors to view the web page in slow motion. :)

#4. Putting images in Embedded Object (Flash or ActiveX Object)

I think this is the best way to protect the image so far. but it is possible to download the whole flash file (*.flv) to local machine by using third-party tool or firefox extensions (eg: Download Helper). So, the individual image are safe from being copied but not for flash.

UPDATED (27th August, 2007):

Watermarking (Thanks to mmhan for reminding me about this.)

AFAIK, there are two ways of watermarking. The first way is that putting a watermark simply on the image. This watermark will be visible to everybody. The second way is that putting a invisible watermark on the image by using Steganography.

Yeah. those are the ways that I remember how people tried to protect their images. If you have other ways, don’t hesitate to let me know.

Remember! All images from the webpage are already sent to the temporary internet files of user’s local machine before showing to the web browser. So, user can still copying images from Temporary Internet File folder. And, What about “Print Screen”? :)

So, if you ask me how to protect the image, I would say “don’t do that!” . :)

ASP.NET: DropDown List problem with IE6

SourceCode Download ~

WebSite7
Hosted by eSnips

Question ~

One member from Codeproject asked ~

Hi all,

There is a small requirement in drop down list. Suppose I have bounded the employee names to the drop down list. Now I am searching for a name “Peter”. So if I press ‘p’ and then ‘e’ it should go to Peter’s name. But it goes to Elizabeth’s name. Is there any solution for that? Could anyone of you please help me on that? I am using .Net version 2.0

Thanks and Regards,
Hariharan C

Solution ~

This issue occurs in Internet Explorer 6 version only. I have tested this issue with the most of browsers (Internet Explorer 7, Firefox 2.0.0.6, Opera 9.2 and Safari 3.0.3 (Windows).) It works fine except IE6. I looked for the solution and I came up with the following code.


var pressedKeyString = "";
var delay = 1000;
var timeID = null;

function move(){
var selectList = document.getElementById('DropDownList1');
var arr = new Array();
var idx = 0;
for(var i = 0; i = pressedKeyString.length){
if(pressedKeyString.toLowerCase() == selectList.options[i].value.substring(0,pressedKeyString.length).toLowerCase()){
selectList.selectedIndex = i;
i=selectList.options.length;
alert(pressedKeyString);
}
}
}
pressedKeyString = "";
}
function foo(e,id){
if(timeID != null)clearTimeout(timeID);
timeID = setTimeout("move();",delay);
var key;
if(window.event) // IE
{
key = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
key = e.which
}
var pressKey = String.fromCharCode(key);
pressedKeyString += pressKey;
}

The main idea of this code is that we will enable the timer to check whether the user is still typing or not. The timer will get clear as long as the user keep on typing. The character that you typed will keep on appending to the string called pressedKeyString. Note that the select list will be changed automatically on IE6 by default while typing. (Ya, this is what we don’t like). After typing finished (timer will count to 1000 minisecound), then the dropdown list will be changed to the option which is matched with the characters that you enter. (eg: if you type “pe” then dropdown list will select to “Peter”.)

Hope it helps. Feel free to let me know if you have any comment or suggestion. Thanks.

Some interesting ASP.NET 2.0 FAQ

I found this post <I’m wondering – asp.net 2.0> on Mayvelous’s blog. I think those questions are very interesting. So, I was thinking to write the reply post for those questions but I didn’t have the exact answer for the generated xml file of .dll. I didn’t have time to find about that too. So, the post was saved as a draft in my blog for long time. I accidentally found this post in wp drafts collection yesterday. I made some changes today and post it here..

Why ASP.NET 2.0 website project does not create project file?

In ASP.NET 1.1, the configuration information of project used to store in *.csproj. If it’s a web project, the URL part is saved in *.webinfo. But it has been changed in ASP.NET 2.0. All of project configuration, path (both absolute part or virtual part) are stored in *.sln file only.

Why ASP.NET 2.0 webproject doesn’t create .dll file? Where all those code-behinds compiled into?

ASP.NET web pages and code files are dynamically compiled on request for the first time. The compiled resources are cached for next time request. So, no need to generate .dll for webproject. But It’s not good pratice and nobody won’t do that on their production server. Once I did it like that to know how bad that is. What I did was that I copied the whole folder of my website from my harddrive and uploaded it in FTP. Then, I tried to browse my website. It was very slow. I didn’t use any thrid-party components in that website. I think it will be more obviously slow if there are some third-party components used in website.

You should precompile your website if you wanna see *.dll file of your project. As you know, Precompilation is new features of .NET 2.0 which allows developers to precompile the entire website for boosting response time of your website.

Advantages of Precompilation (Ref: MSDN )

  • Faster response time for users, since pages and code files do not have to be compiled the first time they are requested. This is particularly useful on large sites that are updated frequently.
  • A means to identify compile-time bugs before users see a site.
  • The ability to create a compiled version of the site that can be deployed to a production server without source code.

More Info ~

>>I’m wondering, if we are to deploy it, do we only deploy .aspx and .ascx (front-end) files or have to include code-behind files as well?

not “have to” but you can if you want. Like I said above, you can include code-behind files in deployment. but it’s not good. Precompilation would be the best.

>>I’m wondering, why .pdb files are also included when you add project references to the website project.pdb files

AFAIK, this .pdb file is automatically generated if the Project configuration is set to “Debug” Mode. This file is used for storing the debugging information and symbols. Honestly, I dont have that much idea about this file. Please check .pdb file – MSDN for more info.

>>I’m wondering, do we need to add those .pdb and .xml along with referenced .dll in the deployment.

No. It’s not required. I’m sure that it’s not required to add those files in deployment but I dont know why xml files are generated. So, I have asked about it in CodeProject Forum. I got the answer as below from Scott Dorman in very short time. (Thank you! scott. )

The *.xml file is the compiler generated XML documentation file. The contents of this file come from the XML comments in the source code.

The *.pdb file is the debugging symbol file, also generated by the compiler. It contains the debugging “symbols” (information) needed by the debugger to be able to match the compiled binary to the source code when you are debugging.

>> I’m wondering, the main difference between asp.net 2.0 web application project and web site project.

AFAIK, asp.net 2.0 web application project is designed for those who wanna keep VS 2003 web project model. But I’m not very interest to use this since it doesn’t support in VS 2005 Express Edition. Here is the good article about Web Application Project and the differences between Web Application Project and Web Project.

Feel free to let me know if you have any comment for those answers. I’m just sharing in the way that I understand. If you have some more idea about those then feel free to discuss with me. Thanks.

Some FAQ from ASP.NET web development

Hello! How are you doing? Today, I wanna share with you some of the notes that I have made while I was working in ASP.NET project. I started playing with .NET since September, 2004. I used to face a lot of problems and have to find the solutions for those problems. I wanna share all of those problems and solutions that I’ve faced. But unfortunately, I didn’t remember all of these since I didn’t make any note in my outlook. Anyway, I’ll share with you what I have in my mail. Hopefully, you may find it useful.

1. How to invoke/fire JS function after validating of ASP.NET validator?

Use “Page.RegisterStartupScript(,)” function as below.

        string strScript   = "";
        strScript += "function foo(){";
        strScript += " alert('This is foo!');";
        strScript += "}";
        strScript += "";Page.RegisterStartupScript("bear",strScript);

2. Is it possible to access the Javascript variable from Server-side?

Follow the steps below if you wanna share something between the client-side script and server-side script.

  1. Add Server-side hidden field in your page.
  2. Set the value of Javascript variable to this hidden field by using document.getElementById() function.
  3. then, get the value of that hidden field.

Note: I used this technique in this sample. You may check it out.

3. Why all data from web controls within the disabled panel has been lost during the postback?

It’s pretty strange. In window-based application, we only need to disable the panel if we want to disable all controls inside this panel. But we can’t do like that in web development. ASP.NET doesn’t keep the viewstate of the controls if the panel is disabled so that all data in those controls within disabled panel will be lost during the PoskBack.
The solution for this problem is that enable or disable each and every controls inside the disabled panel. Enable explicitly.

Scott Mitchell wrote very good article about this problem and solution in this blog.. You may check his article “Panel Weirdness” here.

4. How to set the width of textbox in percentage? [esp: for Firefox users.]

This is the problem that I faced when I was developing cross-browser asp.net web application. What happen was that I wanna set the width of a textbox to 100%. So, I set 100% to the width property of textbox in Design Mode. But the style that i set to textbox doesn’t load in Firefox. It automatically change from 100% to 100. I have no idea why it was happening like that. However, I could come up with the solution for that problem. The solution is that write the style you want as a CSS class in CSS file and set it to the textbox.

5. I used to get this error “Access is Denied: Microsoft.Web.UI.Webcontrols”” very often while running asp.net project from VS.NET IDE.Why?

Solution #1 ~

  • Stop Indexing Service.

[ref: http://support.microsoft.com/default.aspx?scid=kb;en-us;329065]

Details ~

If you do not use Index Server on the server, you can disable it. To do so, follow these steps:
1. Click Start, and then click Services.
2. Locate Indexing Service from the list of services, and then click Indexing Service Properties from the subform.
3. On the General tab of the Indexing Service Properties dialog box, in the Startup type drop-down item list, click Disabled.
4. Click OK.

If you use Index Server, you can exclude the Temporary ASP.NET Files directory from the folders that the Index Server scans. To do so, follow these steps:
1. Click Start, point to All Programs, point to Administrative Tools, and then click Computer Management.
2. Expand the Services and Applications node, expand the Indexing Service node, and then expand the System node.
3. Right-click the Directories folder, point to New, and then click Directory from the subform to open the Add Directory dialog box.
4. Click Browse, and then locate the Temporary ASP.NET Files directory. You typically find the Temporary ASP.NET files in the following path: c:\\Microsoft.NET\Framework\\Temporary ASP.NET Files
Note is the version of .NET Framework installed on your computer.
5. Click No under the Include in Index? option buttons.
6. Click OK to close.
7. Close the Computer Management dialog box.
8. Restart the Indexing Services service.

Solution #2 ~

In the web.config file if the tag identity impersonate=”true” is added, remove it and see. [Don’t ask me why :)] [Ref: http://vadivel.blogspot.com/2006/06/access-is-denied-microsoftwebuiwebcont.html ]

5. I’m using EnterpriseLibrary latest version in my ASP.NET project. I used to get this error message “This schema for this assembly has not been registered with WMI.” while building my web project. Why?

Solution ~

  1. Open up the EnterpriseLibrary.sln and modify the Configuration Properties\Build\Conditional Constants of the EnterpriseLibrary.Common project.
  2. Remove the USEWMI;USEEVENTLOG;USEPERFORMANCECOUNTER constants. By removing these constants, all of the internal Enterprise Library instrumentation will be disabled.
  3. Recompile.

Ref : http://channel9.msdn.com/wiki/default.aspx/Channel9.EnterpriseLibraryFAQ

6. Protecting an ASP.NET page against malicious input with ValidateRequest (A potentially dangerous Request.Form value was detected)

When your project is in testing state, you should try to test your application by entering script tag (eg: <script lanague=”javascript”>) or HTML tag (eg: <html><strong>) or #@ or @# characters. And see what happen.. You may probably get the error.. If you don’t wanna get this error then you have to set the page directive validateRequest to false. Note that your page might has the security problem.

Ref: http://codebetter.com/blogs/peter.van.ooijen/archive/2005/10/21/133505.aspex

That’s all for now. If you have any useful tip for ASP.NET development, you can mail me at mchlsync AT gmail.com with the subject “[Michael Sync’s blog – ASP.NET Tips]”. Thanks a lot.

Related Articles ~

  1. [Tips/Tricks] ASP.NET with SQL Reporting Services
  2. Tips/Tricks – How to control MaxLength of Multiline TextBox in ASP.NET 1.1?

[Tips/Tricks] ASP.NET with SQL Reporting Services

1. Error Message ~ d:\xxxxx\yourwebproject\yourreport.rdl
The value expression used in query parameter ‘@xxx’ returned a data type that is not valid.

Solution ~

  • Remove this parameter from Parameter
  • Rebuild the solution
  • (If you are still getting this error) Close and Reopen Visual Studio IDE ***

………………

2. Error Message ~ Parameter validation failed. It is not possible to provide valid values for all parameters. (rsParameterError) Get Online Help

Solution ~

  • Check “Has default” checkedbox in parameter lists of ReportViewer

***********

3. Problem: Report doesn’t get updated.

Solution ~

  • Add another parameter like “Timestamp” in your viewer.
  • Pass a timestamp field to your report from code.

Note: If you don’t wanna see this parameter “Timestamp” in your reportviewer, put blank for this report. (Be sure that you  have installed all required service packs.)