|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionWelcome to Object Oriented JavaScript class library in C#/.NET style. BackgroundI like coding with JavaScript in object oriented style. But one day I've decided to bring my code into another level and make my JavaScript code to look like C# as much as possible. So I've:
NOTE: This library is not finished yet, contains experimental code parts and was posted here for educational purposes only but you can make clear picture where it goes. You can browse through these JavaScript classes and methods here: http://www.jocys.com/Scripts/Classes/Documents/.
Example: HMAC-MD5 checksumC# code to create HMAC-MD5 checksum: // Create HMAC-MD5 Algorithm;
System.Security.Cryptography.HMACMD5 hmac = new System.Security.Cryptography.HMACMD5();
// Convert string to array of bytes.
byte[] key = System.Text.Encoding.UTF8.GetBytes("test key");
byte[] data = System.Text.Encoding.UTF8.GetBytes("test data");
// Compute hash.
byte hashBytes = hmac.ComputeHash(key, data);
// Convert to HEX string.
string hex = System.BitConverter.ToString(hashBytes);
// Convert to GUID so you can store it inside database.
Guid guid = new System.Guid(hashBytes);
Same HMAC-MD5 checksum code written with this JavaScript library: Include JavaScripts:
// Create HMAC-MD5 Algorithm;
var hmac = new System.Security.Cryptography.HMACMD5();
// Convert string to array of bytes.
var key = System.Text.Encoding.UTF8.GetBytes("test key");
var data = System.Text.Encoding.UTF8.GetBytes("test data");
// Compute hash.
var hashBytes = hmac.ComputeHash(key, data);
// Convert to HEX string.
var hex = System.BitConverter.ToString(hashBytes);
// Convert to GUID so you can store it inside database.
var guid = new System.Guid(hashBytes);
As you can see everything looks prety same.Example: AES-256 encryptionC# code for AES-256 encryption: // Turn input string into a byte array.
byte[] input = System.Text.Encoding.Unicode.GetBytes("Plain Text");
// Create an instance of the Rijndael class.
System.Security.Cryptography.RijndaelManaged cipher;
cipher = new System.Security.Cryptography.RijndaelManaged();
// Calculate salt to make it harder to guess key by using a dictionary attack.
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes("password");
System.Security.Cryptography.HMACSHA1 hmac;
hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
byte[] salt = hmac.ComputeHash(passwordBytes);
// Generate Secret Key from the password and salt.
// Note: Set number of iterations to 10 in order for JavaScript example to work faster.
System.Security.Cryptography.Rfc2898DeriveBytes secretKey;
secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);
// Create a encryptor from the existing SecretKey bytes by using
// 32 bytes (256 bits) for the secret key and
// 16 bytes (128 bits) for the initialization vector (IV).
byte[] key = secretKey.GetBytes(32);
byte[] iv = secretKey.GetBytes(16);
System.Security.Cryptography.ICryptoTransform cryptor;
cryptor = cipher.CreateEncryptor(key, iv);
// Create new Input.
byte[] inputBuffer = new byte[input.Length];
// Copy data bytes to input buffer.
System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
// Create a MemoryStream to hold the output bytes.
System.IO.MemoryStream stream = new System.IO.MemoryStream();
// Create a CryptoStream through which we are going to be processing our data.
System.Security.Cryptography.CryptoStreamMode mode;
mode = System.Security.Cryptography.CryptoStreamMode.Write;
System.Security.Cryptography.CryptoStream cryptoStream;
cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);
// Start the crypting process.
cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
// Finish crypting.
cryptoStream.FlushFinalBlock();
// Convert data from a memoryStream into a byte array.
byte[] outputBuffer = stream.ToArray();
// Close both streams.
stream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string base64String = System.Convert.ToBase64String(outputBuffer);
// base64String = laFf3eKu9tzB2XksJjd8EVM3PA9O30wz0Y+X3nyelW4=
Same AES-256 encryption code written with this JavaScript library: Include JavaScripts:
// Turn input string into a byte array.
var input = System.Text.Encoding.Unicode.GetBytes("Plain Text");
// Create an instance of the Rijndael class.
var cipher = new System.Security.Cryptography.RijndaelManaged();
// Calculate salt to make it harder to guess key by using a dictionary attack.
var passwordBytes = System.Text.Encoding.UTF8.GetBytes("password");
var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
var salt = hmac.ComputeHash(passwordBytes);
// Generate Secret Key from the password and salt.
// Note: Set number of iterations to 10 in order for JavaScript example to work faster.
var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);
// Create a encryptor from the existing SecretKey bytes by using
// 32 bytes (256 bits) for the secret key and
// 16 bytes (128 bits) for the initialization vector (IV).
var key = secretKey.GetBytes(32);
var iv = secretKey.GetBytes(16);
var cryptor = cipher.CreateEncryptor(key, iv);
// Create new Input.
var inputBuffer = new System.Byte(input.length);
// Copy data bytes to input buffer.
System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.length);
// Create a MemoryStream to hold the output bytes.
var stream = new System.IO.MemoryStream();
// Create a CryptoStream through which we are going to be processing our data.
var mode = System.Security.Cryptography.CryptoStreamMode.Write;
var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);
// Start the crypting process.
cryptoStream.Write(inputBuffer, 0, inputBuffer.length);
// Finish crypting.
cryptoStream.FlushFinalBlock();
// Convert data from a memoryStream into a byte array.
var outputBuffer = stream.ToArray();
// Close both streams.
stream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
var base64String = System.Convert.ToBase64String(outputBuffer);
// base64String = laFf3eKu9tzB2XksJjd8EVM3PA9O30wz0Y+X3nyelW4=
Example: User Interfacefunction firstButton_Click(){
Trace.Write("First Button Click");
}
function secondButton_Click(){
Trace.Write("Second Button Click");
}
function Window_Load(){
Trace.IsEnabled = true;
Trace.Write("Start Demo");
// Create toolbar.
var toolBar = new System.Web.UI.Interface.ToolBar("MyToolBar");
// Add toolbar to document.
document.body.appendChild(toolBar.Node);
// Create Bar.
var bar = new System.Web.UI.Interface.Bar("MainBar", document, "Bar Title");
toolBar.Add(bar);
// Create first button.
var firstButton = new System.Web.UI.Interface.Button("FirstButton", document);
firstButton.SetText("First");
firstButton.SetImage("Images/Icons/Options-16x16.png");
firstButton.SetTitle("First Button");
firstButton.customAction = firstButton_Click;
bar.Add(firstButton);
// Create second button.
var secondButton = new System.Web.UI.Interface.Button("SecondButton", document);
secondButton.SetText("Second");
secondButton.SetImage("Images/Icons/Trace.16x16.png");
secondButton.SetTitle("Second Button");
secondButton.customAction = secondButton_Click;
bar.Add(secondButton);
}
window.onload = Window_Load;
Will produce this interface on the web page:
BenefitsCoding with JavaScript in C# .NET style provides these benefits:
RequirementsJavaScript have very limited number of types:
But by combining existing types we can create JavaScript objects similar to C#. For example:
NUMBERS: All numbers in JavaScript are 64-bit (8 bytes) floating point numbers (double: 1-bit sign, 11-bits exponent, 52-bits mantissa). There is no Double, Single/Float, Boolean, Int16, UInt16, Int32 or UInt32. But you can use public static methods of System.BitConverter JavaScript class in order to treat same JavaScript number as different type: // Convert number to [0x00, 0x00, 0xCC, 0xCC] array.
var bytes = System.BitConverter.GetBytes(-859045888, System.TypeCode.Int32);
// Convert bytes back to -859045888.
var n = System.BitConverter.ToInt32(bytes, 0); System.BitConverter JavaScript class supports little-endian (default), big-endian byte orders and numeric arrays. System.BitConverter class is very useful in encoding/decoding/encryption/decryption classes. Please note that you need to specify number type when using GetBytes(value, typeCode) method by using System.TypeCode enumeration values (this enumeration is located inside System.js file).NOTE: You can use <param type="byte[]" name="data">...</param> inside JavaScript XML Comments in order to specify type of input data and <returns type="double">...</returns> - for output. Files from this JavaScript library can be included on client and server side thanks to special header and footer: <!--//--><%
//=============================================================================
// Jocys.com JavaScript.NET Classes (In C# Object Oriented Style)
// Created by Evaldas Jocys <evaldas@jocys.com>
//-----------------------------------------------------------------------------
// You can include this script on both sides - server and client:
// Server: <!-- #INCLUDE FILE="ScriptFile.js" -->
// Client: <script type="text/javascript" src="ScriptFile.js"></script>
//=============================================================================
JavaScript Code Here...
//==============================================================================
// END
//------------------------------------------------------------------------------
//%>
... and by avoiding Response.Write() or alert() use directly: for example: I can detect if script is running on server side or client side and show message accordingly with this code: this.IsServerSide = (typeof(Response) == "object");
// If we are on server side then...
if (this.IsServerSide){
// Write text to output.
Response.Write(text);
}else{
// Show popup message.
alert(text);
}
JavaScript IntelliSenseVisual Studio 2008 have built-in support for JavaScript IntelliSense. This means that if you open System.BitConverter.js file, place cursor at the end of file and type "System.BitConverter." then straight after dot VS 2008 will bring menu containing all available methods and properties of System.BitConverter class:
Good news here that Microsoft is moving into right direction. Bad news that JavaScript IntelliSense works only with specific JavaScript coding style and sometimes needs workarounds. In other words it works in mysterious ways or doesn't work at all :). Some extra upgrades are needed on my code I guess. InstallationExtract source archive into webroot (/) folder of your website. Example: System.Security.PasswordInside source code you can find examples (/Scripts/Classes/Examples/) including password generator example. You can run it:
To make a suggestion or report bugs please write to: evaldas@jocys.com History
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||