Search

StringBuilder in JavaScript

a simple StringBuilder class that pushes individual strings into an array and then uses the join method to produce the concatenated output string.


// Initializes a new instance of the StringBuilder class and appends the given value if supplied
function StringBuilder(value)
{
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
{
if (value)
{
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function ()
{
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function ()
{
return this.strings.join("");
}
//The code is so simple and straightforward that it should be self-explanatory. Now here's an example of how to use it:
// create a StringBuilder
var sb = new StringBuilder();
// append some text
sb.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, ");
sb.append("sed diem nonummy nibh euismod tincidunt ut lacreet dolore ");
sb.append("magna aliguam erat volutpat.");
// get the full string value
var s = sb.toString();

Process Piping

This example shows the technique called as process piping. Process piping is a technique to redirect input/out form a process to get the result in runtime. This enable us to execute any process with a given set of parameters and capture the output. In the example below weare invoking the command shell(cmd.exe) to do a ping on "Bing.com" and capture the output in the console.

void Main()
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("dir"); //Execute ping bing.com
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
static void cmd_Error(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error from other process");
Console.WriteLine(e.Data);
}
view raw Piping.cs hosted with ❤ by GitHub


We can further create a function which does the same for us, and alter the behaviour by sending different parameters.

JavaScript AJAX wrapper

This is a simple code that wraps the XmlHttp Request and Response.
/* Jscript */
function AjaxWrapper()
{
var object = this;
object.Request = NewRequest();
object.Request.onreadystatechange = CompleteRequest;
this.Sync = true;
this.Method = "GET";
this.URL = "";
this.WebServiceMethod = "";
this.Parameters = new ParameterCollection();
this.Execute = ExecuteRequest;
this.AsyncCallbackMethod = null;
this.ResultXML = null;
this.ResultText = null;
function NewRequest()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else
return new ActiveXObject("Microsoft.XMLHTTP");
}
function ExecuteRequest()
{
var parameters = object.Parameters.toString();
ResetRequest();
if (this.Method.toUpperCase() == "POST")
{
if (object.WebServiceMethod.length > 0)
object.Request.open(object.Method, object.URL + "/" + object.WebServiceMethod, !object.Sync);
else
object.Request.open(object.Method, object.URL, !object.Sync);
object.Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
object.Request.send(object.Parameters);
}
else if (this.Method.toUpperCase() == "GET")
{
if (object.WebServiceMethod.length > 0 && parameters.length > 0)
object.Request.open(object.Method, object.URL + "/" + object.WebServiceMethod + "?" + parameters, !object.Sync);
else if (object.WebServiceMethod.length > 0)
object.Request.open(object.Method, object.URL + "/" + object.WebServiceMethod, !object.Sync);
else if (parametres.length > 0)
object.Request.open(object.Method, object.URL + "?" + parameters, !object.Sync);
else
object.Request.open(object.Method, object.URL, !object.Sync);
object.Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
object.Request.send();
}
else
{
throw "The method '" + this.Method.toUpperCase() + "' is not supported !";
}
if (object.Sync)
FinishRequest(object.Request.responseText);
}
function CompleteRequest()
{
if (object.Request.readyState == 4)
{
if (object.Request.status == 200)
{
FinishRequest(object.Request.responseText);
if (object.AsyncCallbackMethod != null)
object.AsyncCallbackMethod();
}
}
}
function ResetRequest()
{
object.Request = NewRequest();
object.Request.onreadystatechange = CompleteRequest;
}
function FinishRequest(retourTexte)
{
var xmlDoc = new ActiveXObject("MSXML2.DOMDocument");
object.ResultText = object.Request.responseText;
try
{
xmlDoc.loadXML(object.Request.responseText);
if (xmlDoc.parsed && xmlDoc.xml.length > 0)
object.ResultXML = xmlDoc;
else
object.ResultXML = null;
}
catch (ex)
{
object.ResultXML = null;
}
}
}
view raw AjaxWrapper.js hosted with ❤ by GitHub

Class in JavaScript

As per Wikipedia: "JavaScript is classified as a prototype-based scripting language with dynamic typing and first-class functions. This mix of features makes it a multi-paradigm language, supporting object-oriented,[6] imperative, and functional[1][7] programming styles." But we still never explore the object orientation side of it, to start with.. we can create Class & Modules to divide the program in small chucks oflogic. This example shows you how to create a class in JavaScript.
/* Jscript */
/* Class in JavaScript */
var ClassName = (function () {
// Constructor
function ClassName(message) {
this.variable1 = message;
}
// Method
ClassName.prototype.greet = function () {
return "Hello, " + this.variable1;
};
return ClassName;
})();
var greeter = new ClassName("world");
view raw Class.js hosted with ❤ by GitHub
As per the above code, we have defined a class which is actually a function since JScript don't have class keyword and a constructor(will be same as the class name). "this" refers to the current object in memory and the variable1 is prototyped to it.

Module in JavaScript

Javascript has always been written with a function oriented structure, as the script goes more dense it become complicate and harder to manage & extend. With Javascript module we can segregate these as logical modules. Here is an example how this can be done in JavaScript.

/* Jscript Module */
var Module;
(function (Module) {
var exportClass = (function () {
function exportClass(message) {
this.greeting = message;
}
exportClass.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return exportClass;
})();
Module.exportClass = exportClass;
})(Module || (Module = {}));
var greeter = new Module.exportClass("world");
view raw Module.js hosted with ❤ by GitHub

Fluent interface in C#

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining [1]). Generally, the context is
1. defined through the return value of a called method
2. self-referential, where the new context is equivalent to the last context
3. terminated through the return of a void context.

So here it code how you can implement Jquery like fluent interface(method chaning) with C# code.

class FluentInterface
{
private StringBuilder _sbl;
public FluentInterface()
{
_sbl = new StringBuilder();
}
public FluentInterface Add(string variable)
{
_sbl.AppendLine(variable);
return this;
}
public FluentInterface Replace(string oldValue,string newValue)
{
_sbl.Replace(oldValue, newValue);
return this;
}
public FluentInterface Print()
{
string[] DataArray = new List<string>(Regex.Split(_sbl.ToString(), Environment.NewLine)).ToArray();
DataArray.ToList().ForEach(x=&gt;Console.WriteLine(x));
return this;
}
public FluentInterface Clear()
{
_sbl.Clear();
return this;
}
}

Here i have chained the method using a class called "FluentInterface", which implements the StringBuilder and provided a set of method, which are chained together. This implements JQuery like accessability in c#. The function can be called as:
 

 new FluentInterface().Add("line1").Add("line2").Replace("line2","line456").
Add("line3").Add("line4").Add("line5").Print().Clear();