Devanand

a versatile blog


Leave a comment

javascript module pattern – snake and ladder example


Module pattern – Modular code having a relative functionality in one capsule in one place.

We can organize code in a module in such a way that the only necessary methods we can expose to a client and rest all private. In short, we are doing Encapsulation.

Below is the general structure of module pattern-

var Module = (function(){ //Module

//private members

var privateVar = ‘value’;

var privateMethod = function() {

}

return { //public methods

publicMethod1 : function() {

}

}

})(); //IIFE

 

In this blog, I have taken an example of snake and ladder game using module pattern.

For snake and ladder game we need board, dice, and players.

An alternate player can throw/roll dice and depend upon the value player can move further.

Some constraints are in between the route in the form of snakes and ladders which will pull down or up the user’s position.

So keeping in mind the above requirement I have created the board (InitUI), configured players, snakes, ladders as

private members, and attached the RollDice function of Module to Roll button.

So finally, my snake-ladder module looks like below.

 

var SnakeLadderModule = (function(){

var snakes, ladders, players ..configuration

return {

Init: init,

RollDice: rollDice

};

})();

 

Output-

Snake and Ladder game

 

Code:

varsion 1: https://jsfiddle.net/sugsyybw/1/

varsion 2: https://jsfiddle.net/sugsyybw/2/

 

Bugs in version 2:

  1. Cell width and height need to adjust according to the background image.
  2. Currently game is not responsive
  3. Players are not following the path. It directly jumps to the destination.


Leave a comment

Polymorphism in C#


In object-oriented programming languages such as c#, java etc., we can achieve run-time polymorphism. Here in this blog I am explaining the run-time polymorphism which is achieved using access modifiers like virtual, override and abstract using c#.

For better understanding, I have taken an example of baseclass and childclass inheritance tree and both classes have Print method.

 

Let say for the declaration of  Base obj = new Child(); below is the memory representation of stack memory and managed heap.

Here Base type pointer is in stack memory pointing to the address space of Child object and new keyword allocates memory space in heap aria.

Now depending upon the access modifiers used for method Print the respective Print function gets called.

Below table shows the various combinations of access modifiers of Print method and the output result.

e.g.

Condition 1: If Base class having keyword virtual or new or na and Child class having keyword virtual

then for Base B = new Child();

B.Print() will print Base on a console.

This is happening due to the static resolution of the function call (early binding). The base pointer still pointing to the base Print function.

 

Condition 2: If Base class having virtual modifier and Child class having override

then for Base B = new Child();

B.Print() will print Child on a console.

This is happening due to dynamic linkage or late binding of the function call. Now the base pointer will point to the function whose instance is assigned to variable B.

 

  • virtual keyword is used to modify methods, properties, events etc. and allow to be overridden in derived class.

This keyword can not be used with static, private, abstract and override keywords.

  • override keyword allows us to modify methods, properties, events etc.
  • new keyword is used to hide method of derived class.

 

Compile time errors-

  1. If any class is abstract then need to implement its abstract methods using override modifier in inherited class – ‘ChildClass’ does not implement inherited abstract member ‘BaseClass.Print()’
  2. If any class having modifier override to any method must have virtual, abstract or override a method declared in base class – ‘ChildClass.Print()’: cannot override inherited member ‘BaseClass.Print()’ because it is not marked virtual, abstract, or override


Leave a comment

Parse stackoverflow website using c#


To parse any website same as we are parsing DOM elements using jQuery using various selectors, in C# you can take help of HtmlAgilityPack.

To install HtmlAgilityPack, run the following command in the Package Manager Console

pm > Install-Package HtmlAgilityPack

snippet 1: Define a model of your repository.

SOModel.cs

public class StackOverflow
{
public int Id { get; set; }
public string SOurl { get; set; }
public string Question { get; set; }
public string Answer { get; set; }
public DateTime CreatedOn { get; set; }
}

 

snippet 2: Get the HTML document of an url and load it. Select required divs using QuerySelectorAll method of agility pack

Code.cs

using HtmlAgilityPack;

string urlAddress = "http://stackoverflow.com/questions/xxx";

StackOverflow soObj = new StackOverflow();
#region Code2 - parsing logic of StackOverflow

soObj.SOurl = urlAddress;

HtmlWeb web = new HtmlWeb();
HtmlDocument document = web.Load(urlAddress);

//to get Question Text
HtmlNode[] qnodes = document.DocumentNode.QuerySelectorAll("#question .postcell").ToArray();
foreach (HtmlNode item in qnodes)
{
soObj.Question = item.InnerHtml;
}

// to get Answer which is marked and accepeted
HtmlNode[] anodes = document.DocumentNode.QuerySelectorAll("#answers .answer.accepted-answer").ToArray();
foreach (HtmlNode item in anodes)
{
soObj.Answer = item.InnerHtml;
}
soObj.CreatedOn = DateTime.Now; //your creation date time
#endregion
db.StackOverflows.Add(soObj);
db.SaveChanges();

 

Technologies used: HtmlAgilityPack, C#, Entity Framework


Leave a comment

excel formula with intellisense using javascript, jquery plugin


This post contains plugin for displaying an excel formula list and formula intellisense while typing.

While working on online excel feature using Handsontable I came across the situation where I need an Excel Formula Intellisence.

I started searching exactly the same but couldn’t make it, so after lot of googling I got the core tokenizer for my formula string to parse.

Thanks to ewbi for sharing formula tokenizer code.

I decided to write plugin in my own way.

Below are the steps to make your input box work like excel formula intellisense.

Step 1. You will required jquery – google CDN

 

Step 2. Add jquery plugin link (code file shared below)

Step 3. Take html input field for which you want to apply excel formula

Add some styling:

.exltooltip {
 background-color:#000;
 border:1px solid #fff;
 padding:5px;
 width:440px;
 display:none;
 color:#bbb;
 text-align:left;
 font-family:Calibri;
 font-size:14px;
 
 /* outline radius for mozilla/firefox only */
 -moz-box-shadow:0 0 4px #000;
 -webkit-box-shadow:0 0 4px #000;
}
.exltooltip b {
 color:#fff;
}

Step 4. Call the plugin using below code

$(“#tbExel”).ExcelFormulate();

Thats it!

Output:

excelformulaintellisence

———————

You can also make customization in plugin code using setting.

I also shared the source code.

excelformulaplugin-1

— or —

jsfiddle code:

Version 1: jsfiddle Initial

———————

TODO:

1. Bold current argument of current formula done on 29th Jun 15

2. Access to default plugin settings done on 25th Jun 15

3. Position of formula tooltip

4. Chaining done on 25th Jun 15

5. Replacement of dropdown select options control with div / ul li

6. Multiple instance support (known issue)

7. Check in list of selector  whether target is input box or textarea (known issue)

8. Similar Id issue (known issue)

9. Browser Compatibility

Do not forgot to share your thoughts. 🙂


14 Comments

Compress json at client side and decopress using C#, gzip


This post consist of two parts which will let you know how to send large amount of data by compressing it at client side and decompress it at server side using LZ algorithm.

Part 1: compression, decompression of json data

Need to speed up website by sending compressed json data then use lz-string library.

reference: http://pieroxy.net/blog/pages/lz-string/index.html

Compression and decompression code available in javascript (client side) and C# (server side) as well.

So you can compress and decompress data at either end while sending over TCP channel. Both code uses same algorithm.

Below code give you better illustration.

Step 1: Include script url to page

<script type="text/javascript" src="lz-string.js" ></script>

Step 2: Compress json data using lz-string.js at client side

// Use compressToUTF16 function to compress at client side
// Because decompression at server side will work properly with UTF16
var compressedData = LZString.compressToUTF16("Your Large JSON stringified data");
var myURL = "your URL";
var pageId = "Other Normal Data";
$.ajax({
type: "POST",
url: myURL,
data: {
lzStringData: compressedData,
pgId: pageId
},
async: true,
success: function (data, status) {
// wow!
},
error: function(data) {
// your error handling
}
});

While sending compressed data over TCP channel you can not able to see in plain format, because of UTF conversion so not able to read in fiddler.

Step 3: Uncompress you string and get the original at server side using C#

[HttpPost]
[ValidateInput(false)]
public string DecompressJson(string lzStringData, int pgId)
{
var jsonStr = LZString.decompressFromUTF16(lzStringData);

//process jsonStr using JsonArray, JsonValue, JsonObject
return "OK";
}

Note: Other libraries like LZW, LZMA, GZIP are not compressing much as compared to LZ-string, so I recommend to use this.

For further compression of data use GZip/Deflate compression.

Part 2: GZipping data-

How it works- If browser supports GZip/Deflate then it sends Accept-Encoding: gzip, deflate to server, and server responds back using Content-Encoding: gzip

1: Send gzip data to server using jquery ajax

$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Encoding", "gzip");
},

2: Send GZip content from IIS to client side use HttpModule or CustomAttribute

Use HttpModule to send the GZipped css and js files and make them cache able.

Use CustomAttribute to GZip response of controller method.

public class GZipContentAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext) {
string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
if (AcceptEncoding.Contains("gzip")) {
Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress);
Response.Headers.Remove("Content-Encoding");
Response.AppendHeader("Content-Encoding", "gzip");
}
else use DeflateStream
}
}

Decorate controller method with the attribute [GZipContent] so that response get encoded
Note: GZip or deflate both take CPU time to compress data, so use GZip/Deflate compression if required.

Download Code


Leave a comment

Use custom encryption/decryption c# library in SQL Server


Many times we are doing some important but time consuming part into the business layer like password, querystring encryption/decryption, custom changes on data.

So, if we want to speed up these type of functionality then we can go for the solution like referring the c# dll into SQL Server.

This post will explain you How to register the dll and how to use  the functionality.

Scenario:  Custom Encryption/Decryption of password from database side.

Steps:

1. Create the library of encryption and decryption into C#.Net

File->New->Project->Database->SQL Server

Choose 2005/2008 database project

Add your custom logic into class file and build the project.

 

2. Following are the steps to register the dll and creating function in SQL Server

A.

exec sp_configure

exec sp_configure ‘clr enabled’, 1;

reconfigure

B.      

alter database [DBName]

set trustworthy on

C.

create assembly [AssemblyName]                              –Eg. Name of Assembly

from ‘C:\SqlServerProjectCustom.dll’                             –Eg. Path of the dll library

WITH PERMISSION_SET = UnSAFE

 

3. Create database functions

CREATE FUNCTION dbo.CustomDecrypt (function Name) ( @s nvarchar(3000) )

RETURNS nvarchar(3000)

as external name

(use of method from dll )

AssemblyCustomEncryption.[SqlServerProjectCustom.UserDefinedFunctions].CustomEncryption

go

 

Usage: Use the transact SQL to encrypt/decrypt values

SELECT dbo.CustomDecrypt(‘Xt7ddLYyKbFxiwL6i+TkAw’)            –Will give select decrypted text

 

 

 


Leave a comment

nth Highest or lowest salary


Most of the time interviewer will ask the question to find the 2nd Highest salary or nth Lowest salary.

Using the below schema create ‘Emp’ table

id             int                   Unchecked
Name     nchar(10)    Checked
sal           money           Checked
manid    int                   Checked

Insert some records into table with some duplicate entries of salary.

Set the n and isHigh variables.

Below code will give you the Highest and Lowest nth salary from ‘Emp’ table

--nth HIGH/LOW salary Works for Int, Money datatypes
DECLARE @n INT
DECLARE @isHigh BIT
SET @n = 2
SET @isHigh = 1
IF (@isHigh = 1)
BEGIN
--One way, giving highest nth salary
SELECT TOP(1) sal AS Salary FROM (SELECT DISTINCT TOP (@n) sal FROM Emp ORDER BY sal DESC) AS salary ORDER BY sal ASC
END
ELSE
--Another way, giving lowest nth salary
SELECT MIN(sal) AS Salary FROM (SELECT DISTINCT TOP (@n) sal FROM Emp ORDER BY sal) TempEmp


Leave a comment

View binary image in sql DB with ASP.net using HttpHandler


Sometimes the images get stored into the database, so we need HttpHandler to get that binary image BLOB.

Below code will help you to get the image from sql DB.

1. HTML Code:

//recommended/best option if number of images per page are more

<img src=’../Shared/ImageHandler.ashx?id=<%#Eval(“ImageID”) %>&UserId=<%=Session[“LoggedInUserId”].ToString() %>’ width=”120″ height=”100″ style=”border:0;” />

or

//aspx page have its own page life cycle events, so this option is not good

<img src=’../Shared/ImageHandler.aspx?id=<%#Eval(“ImageID”) %>&UserId=<%=Session[“LoggedInUserId”].ToString() %>’ width=”120″ height=”100″ style=”border:0;” />

2. httpHandler:

public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int UserId = int.Parse(context.Request.QueryString["UserId"]);
EFF_Database.Image image = new ImageManager(UserId).GetOneImage(int.Parse(context.Request.QueryString["id"]));

//I used entity EFF – you can use simple code like simple SELECT statement
//SqlConnection connection = new SqlConnection(“Your Connection String …”);
//connection.Open();
//SqlCommand command = new SqlCommand(“select Image from Image where ImageID=”+int.Parse(context.Request.QueryString[“id”]), connection);
//SqlDataReader dr = command.ExecuteReader();
//dr.Read();
//context.Response.BinaryWrite((Byte[])dr[0]);
//connection.Close();
//context.Response.End();

byte[] imgbytes = image.ImageFile;
string imgtype = null;
if (image.ImageType != null)
imgtype = image.ImageType.Name;
try
{
//Check the image type if needed
if (imgtype == "PNG")
{
using (MemoryStream ms = new MemoryStream(imgbytes))
{
using (Bitmap bm = new Bitmap(System.Drawing.Image.FromStream(ms)))
{
bm.Save(context.Response.OutputStream, ImageFormat.Png);
}
}
}
else if (imgtype == "JPG")
{
using (MemoryStream ms = new MemoryStream(imgbytes))
{
using (Bitmap bm = new Bitmap(System.Drawing.Image.FromStream(ms)))
{
bm.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
else
{
context.Response.ContentType = imgtype;
context.Response.BinaryWrite(imgbytes);
}
}
catch (Exception ex)
{
//handle the exeption
}
context.Response.End();
}
}


Leave a comment

SQL Cursor to alter columns with constraint


This blog is about the SQL Cursor, how to define it and use to alter the table column name with constraints.

Below code will give you the clear understanding of SQL cursor.
It alters the column name and add the DEFAULT constraint to data type BIT.

Transact SQL:

DECLARE @TableName sysname
DECLARE @Query nvarchar(max)
DECLARE @Act_con nvarchar(max)
DECLARE @Arc_con nvarchar(max)
--1. Declare cursor
DECLARE tableName_cursor CURSOR FAST_FORWARD FOR
SELECT name FROM sys.tables
--2. Open cursor
OPEN tableName_cursor
--3. Fetch to get first resultset
FETCH NEXT FROM tableName_cursor INTO @TableName
--Looping
WHILE @@FETCH_STATUS = 0
BEGIN


set @Act_con = @TableName + '_Active_Con'
set @Arc_con = @TableName + '_Archieved_Con'


--Start here -> alter columns with constraint
SELECT @Query = 'ALTER TABLE [' + @TableName + '] ADD CONSTRAINT ' + @Act_con + ' DEFAULT 1 for IsActive;' +
'ALTER TABLE [' + @TableName + '] ALTER COLUMN IsActive BIT NOT NULL;' +
'ALTER TABLE [' + @TableName + '] ADD CONSTRAINT ' + @Arc_con + ' DEFAULT 0 for IsArchived;' +
'ALTER TABLE [' + @TableName + '] ALTER COLUMN IsArchived BIT NOT NULL'
--End here

BEGIN TRY
EXEC SP_EXECUTESQL @Query
SELECT 'Success : ' + @TableName
END TRY
BEGIN CATCH
--Handle the exceptions
SELECT 'Error in ' + @TableName + '::' + ERROR_MESSAGE()
END CATCH
--4. Fetch next resultset
FETCH NEXT FROM tableName_cursor INTO @TableName
END
--5. Close and deallocate the cursor
CLOSE tableName_cursor
DEALLOCATE tableName_cursor

Their are several constraints in SQL server,

  • Null / Not null
  • Primary key
  • Foreign key
  • Check
  • Default
  • Unique

We can add, alter or drop the constraints.

 

Ref:
To know more about SQL cursors refer: http://msdn.microsoft.com/en-us/library/ms180169.aspx


Leave a comment

SQL jobs


SQL jobs are very useful when we want to perform any database operation, send any notification mail, create event logs depending upon certain duration of time. It is simply a timer which works on system time. We can also compare it with System Scheduler.

In order to create SQL job we have to follow below steps,

1. In object explorer of SQL Server Management studio, expand the SQL Server agent.
>Create New SQL job
>Fill the necessary information and finish by pressing OK button.

2. Now start the SQL job. On start it will show you popup to start the SQLAgent service.

If you want to execute stored procedure from SQL job then in Steps property add following command,
EXEC [dbo].[SP_Name]

You can schedule the job in Schedules section.
e.g. Time, Interval, Priority etc.

To send some important notifications then we have Alerts and Notifications Section.
Where you can specify email ids too.