Monday, August 12, 2013

Javascript shift(), unshift(), pop(), push(), concat(), splice() functions

Hi to day i'll digg into shift(), unshift(), pop(), push(), concat(), splice() functions of javascript :


var arr, alphaNumeric;

var alpha = ['A', 'B', 'C'];
var numeric = [10, 20, 30];
arr = alpha;
console.log('ORIGINAL ARRAY: '+ arr);

// SHIFT
var shifted = arr.shift();
console.log('SHIFTED: '+ shifted);
console.log('ARRAY AFTER SHIFT: '+ arr);

// UNSHIFT
var toUnshift = ['D'];
arr.unshift(toUnshift);
console.log('UNSHIFTED: '+ toUnshift);
console.log('ARRAY AFTER UNSHIFT: '+ arr);

// POP
var popped = arr.pop();
console.log('POPPED: '+ popped);
console.log('ARRAY AFTER POP: '+ arr);

// PUSH
var toPush = ['Z'];
arr.push(toPush);
console.log('PUSHED: '+ toPush);
console.log('ARRAY AFTER PUSH: '+ arr);

// CONCATE
alphaNumeric = alpha.concat(numeric);
console.log('ARRAY: '+ arr);
console.log('ALPHA: '+ alpha);
console.log('NUMERIC: '+ numeric);
console.log('ALPHANUMERIC: '+ alphaNumeric);
alphaNumeric = alpha.concat(1, [2, 3]);
console.log('NEW ALPHANUMERIC: '+ alphaNumeric);

// SPLICE
var startingIndex = 2, howManyToRemove = 2;
var elementsToAdd = ['P'];
var removed;
var minVal = Number.MIN_VALUE, maxVal = Number.MAX_VALUE;

//removed = alphaNumeric.splice(); // does nothing
//removed = alphaNumeric.splice(startingIndex); // removes all from the given index
//removed = alphaNumeric.splice(startingIndex, howManyToRemove); // removes 'n' from the given index
removed = alphaNumeric.splice(startingIndex, howManyToRemove, elementsToAdd); // removes 'n' from the given index, and then add new elements
//removed = alphaNumeric.splice(startingIndex, minVal);
//removed = alphaNumeric.splice(startingIndex, maxVal);

//console.log('minVal: '+ minVal);
//console.log('maxVal: '+ maxVal);

console.log('SPLICED: '+ removed);

console.log('ARRAY AFTER SPLICE: '+ alphaNumeric);

Friday, April 19, 2013

Custom setInterval() function javascript or jquery

Hello friends,

At some point of my jquery problem, i wanted to call a particular funtion 'n' times and in 'x' interval(in seconds). I relied on javascript's setInterval() method, but the catch is that it is called forever.

So I've made a jquery function which does the functionality as requiered by user.

var main = {};
// the funtion definition ...
main.TimerFunction = function (opts) {
// interval in seconds ...
var intervalTime = opts.IntervalInSeconds * 1000;
// cutomized setInterval method ...
var intervalId = setInterval(function () {
   // if the functionToExecute is to be called forever ...
   if ((opts.CallForever != undefined) && (opts.CallForever == true)) {
        opts.FunctionToExecute();
   }

   // if functionToExecute is to be called "n" times ...
   else if ((opts.TimesToCall != undefined) && (opts.TimesToCall != 0)) {
       for (var i = 0; i < opts.TimesToCall; i++) {
                opts.TimesToCall = opts.TimesToCall - 1;
                opts.FunctionToExecute();
                clearInterval(intervalId);
                main.TimerFunction(opts);

                break;
       }
   }                    

   // else clear intervalId ...
   else {
       clearInterval(intervalId);
   }
}, intervalTime);
};




Now if i want to execute a funtion just 3 times at the interval of 5 seconds, i'll  call the above function as :
var params = {};
params.FunctionToExecute = function () {
      alert('Hello World !');
};
params.CallForever =
false;     // true, if you want to call it forever ...
params.TimesToCall = 3;         // calling the FunctionToExecute 3 times ...
params.IntervalInSeconds = 5;   // FunctionToExecute will be called every 5 seconds ...
main.TimerFunction(params);     // pass the parameters, and call the function ...



Enjoy,

Wednesday, April 17, 2013

Calling a method in string in asp.net c#, like eval() in javascript

Sometimes, in ASP.Net and C# you need to call a particular method in a string dynamically, and then process the results if returned. For this we need to make use of : 

 
 
/// Summary: This function executes the given method in the namespace provided.
/// Param name="nameSpace" : Full namespace where the function exists.
/// Param name="constructorArgs": Arguments for the constructor (if any, else pass null).
/// Param name="methodName" : Name of the method to execute. Make sure the method is public.
/// Param name="methodArgs" : Arguments for the constructor (if any[in the same sequence], else pass null).
/// Returns : Returns back any object from that method (if any).
public static object InvokeThisMethod(string nameSpace, object[] constructorArgs, string methodName, object[] methodArgs)
{
 Type type = Type.GetType(nameSpace);
 object instance = Activator.CreateInstance(type, constructorArgs);
 MethodInfo method = type.GetMethod(methodName);
 return method.Invoke(instance, methodArgs);
}
 


For example: Consider these methods -

namespace Test
{
  public class Methods
  { 
    public void Method1() { // foo1 ...  }
    public void Method2() { // foo2 ...  }
    public void Method3() { // foo3 ... }
  }
}



Now in a situation, i want to call these methods(depending on the iteration) from a loop, I can call these methods as:

for (int i = 1; i <= 3; i++)
{  object[] obj = new object[] { };
  string methodName = "Method" + i;               
  InvokeThisMethod("Test.Methods", null, methodName, obj);
}




Enjoy,
 

Thursday, March 21, 2013

What is jquery one function?

jQuery one() is a function which provides single-use event handling. By single-use I mean that the event will be executed/handled only once.
For Example:

$('YOUR_SELECTOR').one('click', function(){
     alert('1. This message will be displayed only once.');
});
http://api.jquery.com/one/

Interestingly the same functionality can be executed by jQuery on() function , as follows:

$('YOUR_SELECTOR').on("click", function(event) {
    alert('2. This message will be displayed only once.');
    $(this).off(event);
});
http://api.jquery.com/on/


Thank You,

Friday, October 24, 2008

How To Get Query-String Values From Javascript ?



function GetQueryStringValueFor(key)
{
var valueToReturn="";
var query = window.location.search.substring(1);
var parms = query.split('&');
for(var i=0 to parms.length)
{ var pos = parms[i].indexOf('=');
if (pos > 0)
{
if(key==parms[i].substring(0,pos))
{
valueToReturn = parms[i].substring(pos+1);
}
}
}
return valueToReturn;
}

Monday, October 13, 2008

How to get last day of the last month with asp.net

///


/// Returns the last date of the previous month in yyyy-MMM-dd format...
///
/// Date to get the last date of its previous month

///

public string GetLastDate(DateTime dt_now)
{
string str_Last = "";
DateTime dt_Last = new DateTime();
int _Day = 0;
_Day = dt_now.Day;
TimeSpan ts = new TimeSpan(_Day, 0, 0, 0, 0);
dt_Last =
dt_now.Subtract(ts);
str_Last = dt_Last.ToString("yyyy-MMM-dd");
return
str_Last;
}



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Wednesday, October 8, 2008

How to download PDF on Button click using asp.net

// html part ...

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Download Filestitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button ID="Button_Download" runat="server" Text="Download" OnClick="Button_Download_Click" />

div>

form>

body>

html>


// code part ...

protected void Button_Download_Click(object sender, EventArgs e)

{

string str_FilePath = Server.MapPath(".") + @"\UploadedItems\Docs\CV.pdf";

System.IO.StreamReader sr = new System.IO.StreamReader(str_FilePath);

Response.BufferOutput = true;

Response.AppendHeader("content-disposition", "attachment; filename=v.pdf");

Response.ContentType = "application/pdf";

Response.TransmitFile(str_FilePath);

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Monday, October 6, 2008

Post your ideas in the blog, when they are fresh and alive

Earlier in the last article, we have discussed a few topics about writing a good blog. So now we'll be discussing about those points being told in that article.
Its quiet important to note that we should write the ideas when they are fresh, that is, they just came to your mind.
Because as you open your mind you feel like as if you are in heaven, and then great ideas will definitely come to your mind. It doesn't matter whether you need to medicate yourself to open your mind. It can be done while meeting someone, or may be when you are dining in a restaurant, or may be when you are traveling around.
So always try to put your maximum effort to visualize more and write accordingly.

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Saturday, October 4, 2008

All about a good blog writing, to come up in search engines


For writing a good blog, we should note a few points ...

  • Post your ideas in the blog, when they are fresh and alive
  • Write with passion, as if you are in the blog
  • Stay on the same topic on which you are blogging
  • Be informative and descriptive in your blog
  • Be clear, simple and user-friendly while blogging
  • Stick to a schedule
  • Don't use old news in the blog
  • Make world know your opinion
  • Don't try to show perfectionism in the topic, stay grounded
  • Mantain your flow of writing in the blog
  • Write the blog in points
  • Be consistent in your blogging style
  • Post with specific keywords in the blog
  • Do make use of the sub-headings in the blog
  • Show genuine interest of the topic in your blog
  • Post the blog with specific keywords
  • Try to use the simplest structure possible for your blog
  • Your frequency of blogging
  • Wite the blog with a feel-good factor
  • The blog content should be syntactically correct, i.e check the spellings
  • Make the blog popular among your circle, i.e advertise your blog
  • Provide RSS and XML feeds of your blog
  • Most importantly, link your blog like crazy
This is just a list of Do's & Don'ts which I've gone through, and you will see your blog getting higher positions in the search engine's result.

All these points I'll be discussing in the coming days, so as to provide a good knowledge of blogging to the youngsters ...


-
ShriKrishna Bhardwaj , Code Less With ASP.Net, SQL Server, Javascript

Tuesday, September 30, 2008

Upcoming Microsoft Visual Studio 2010, Rosario

While reading to some article yesterday ...
I came across the new version of the Visual Studio of Microsoft, the Visual Studio Team System (VSTS) 2010, code-named Rosario.

The VSTS 2010 is expected to be equipped with .Net framework 4.0, and jQuery.

Microsoft plans to focus on five areas: riding the next-generation platform wave, inspiring developer delight, powering breakthrough departmental applications, enabling emerging trends such as cloud computing, and the Application Lifecycle Management (ALM).

Additionally, Microsoft also announced that VSTS 2010 will provide a unified VSTS Development and Database product. Any customer with Visual Studio Team System 2008 Development Edition or Visual Studio Team System 2008 Database Edition and a service contract will be able to get a free upgrade to Visual Studio Team System 2008 Development Edition or Database Edition.

You can find more on : http://msdn.microsoft.com/en-us/vstudio/bb725993.aspx

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Thursday, September 25, 2008

Calling Server-Side(ASP.Net) Method from Client-Side(Javascript)

.ASPX Code ...

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test_ClientToServerPostback.aspx.cs"

Inherits="test_ClientToServerPostback" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Calling Server-Side Method from Client-Side Javascript.title>
<script type="text/javascript">
function LookUp()
{
var lbl = document.getElementById("TextBox1");
CallServerMethod(lbl.value, "");
}

function ReturnedServerData(retValue)
{
document.getElementById("Label1").innerHTML = retValue;
}
script>
head>
<
body>
<form id="form1" runat="server">
<div>
Try Writing : accept/reject <br/> and see the result.<br />
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox><br />
<a href="#" onclick="LookUp();">ClickMea><br />
<br />
<asp:Label ID="Label1" runat="server">asp:Label>
div>
form>
body>
html>

===============================

.CS Code ...

using System;
using System.Web.UI;

public partial class test_ClientToServerPostback : System.Web.UI.Page, ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReturnedServerData", "context");
String callbackScript = "function CallServerMethod(arg, context)" + "{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServerMethod", callbackScript, true);
}
}

public void RaiseCallbackEvent(String eventArgument)
{
if (eventArgument.Trim() == String.Empty)
{
returnValue = "Sorry, please write somthing in textbox.";
}
else
{
if (eventArgument == "accept")
{
returnValue = "Congrats, for accepting!";
}
else if (eventArgument == "reject")
{
returnValue = "You have succesfully rejected !";
}
else
{
returnValue = "You have entered : " + eventArgument + ".";
}
}
}

public String GetCallbackResult()
{
return returnValue;
}
}

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Tuesday, September 16, 2008

Populating Second DropDownList With Another DropDownList !

DropDownList2.DataSource = dt;
DropDownList2.DataValueField = dt.Columns["property_type"].ToString();
DropDownList2.DataTextField = dt.Columns["property_type"].ToString();
DropDownList2.DataBind();

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Tuesday, August 19, 2008

Textbox Keyboard Enter Press Execution in ASP.Net

// Client Function Execution By Hitting Enter-Key of Keyboard ...


TextBox_Search.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + Button_Search.ClientId + "').click();return false;}} else {return true}; ");

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Thursday, August 7, 2008

Loading Gmap from serverside

string lat = "",lat = "";


private void loadmap()
{

HtmlGenericControl Body = this.Master.FindControl("myBody") as HtmlGenericControl;
try
{
if (Body != null)
{
string loadString = "mapload('" + lat + "','" + lng + "','NameOfLocation','./Image/Image.jpg')";
Body.Attributes.Add("onLoad", loadString);
Body.Attributes.Add("onunload", "GUnload()");
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Monday, May 19, 2008

Setting Homepage Using JavaScript

function setasHome()
{
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage('www.url.com');
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Adding a bookmark in browser using JavaScript

function CreateBookmarkLink() {
title = "TitleForBookmark";
url = "www.url.com'';
if (window.sidebar) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
} else if( window.external ) {
// IE Favorite
window.external.AddFavorite( url, title);
}
else if(window.opera && window.print) {
// Opera Hotlist
return true; }
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Wednesday, March 12, 2008

JavaScript Object Notation

JSON (JavaScript Object Notation)
JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with {(left brace) and ends with} (right brace). Each name is followed by: (colon) and the name/value pairs are separated by, (comma).


An array is an ordered collection of values. An array begins with [(left bracket) and ends with] (right bracket). Values are separated by, (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, which completely describe the language.

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.
var myJSONObject = {"bindings":
[
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.
Members can be retrieved using dot or subscript operators.
myJSONObject.bindings[0].method // "newURI"
To convert a JSON text into an object, use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure.
var myObject = eval('(' + myJSONtext + ')');
The eval() function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval() is indicated when the source is trusted and competent. This is commonly the case in web applications when a web server is providing both the base page and the JSON data. There are cases where the source is not trusted. In particular, clients should never be trusted.
When security is a concern it is better to use a JSON parser. A JSON parser will recognize only JSON text and so is much safer:
var myObject = JSON.parse(myJSONtext, filter);
The optional filter parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the filter() function. This can be used to reform generic objects into instances of classes, or to transform date strings into Date objects.
myData = JSON.parse(
text, function (key, value) {return key.indexOf('date') >= 0 ? new Date(value) : value; });
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.
var myJSONText = JSON.stringify(myObject);
If the stringify() method sees an object that contains a toJSON() method, it calls the method, and stringifies the value returned. This allows an object to determine its own JSON representation.
The stringify() method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text. Otherwise, all of the properties of the object will be included. In any case, values that do not have a representation in JSON (such as functions and undefined) are excluded.

Monday, March 10, 2008

Friday, February 22, 2008

Javascript Client Side Page Validation

// In .cs file …

btn_register.Attributes.Add("onclick", "javascript:return ValidateForm()");

=======================================

// In .aspx file in script …

function ValidateForm()

{

//debugger

var p = document.getElementById( "ctl00_ContentPlaceHolder1_txt_phone").value;

var q = document.getElementById ("ctl00_ContentPlaceHolder1_Check_accept");

var fname = document.getElementById ("ctl00_ContentPlaceHolder1_txt_firstname");

var email = document.getElementById ("ctl00_ContentPlaceHolder1_txt_email_id");

var pwd = document.getElementById ("ctl00_ContentPlaceHolder1_txt_password");

if(fname.value=="")

{

alert("Please Enter First Name.")

return false

}

else if(email.value=="")

{

alert("Please Enter Email-ID.")

return false

}

else if(pwd.value=="")

{

alert("Please Enter Password.")

return false

}

else if(!q.checked)

{

alert("You Must Agree Terms \& Conditions To Get Registered.")

return false

}

else if ( document.getElementById (" ctl00_ContentPlaceHolder1_txt_phone" )!="")

{

var num=" ";

chkD = 0

if(p > "")

{

num = p;

}

for (var i = 0; i <>

{

var oneChar = num.charAt(i)

if (oneChar == "." && chkD == 0)

{

chkD = 1

continue

}

if (oneChar < "0" || oneChar > "9")

{

alert("Please Enter Some Valid Phone Numbers.")

return false

}

}

}

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Friday, February 1, 2008

Opening a Pop-Up Window

//Add this to the Page_Load() ...

Button_ToOpenPopupWindow.Attributes.Add ("onclick", "window.open ('PopUp_WindowToOpen.aspx', null, 'height=600, width=460, status= yes, resizable= no, scrollbars=no, toolbar=no, location=no, menubar=no, minimize=no '); ");


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript