September 26, 2012

FIXED: "IE: Microsoft JScript runtime error: 'JSON' is undefined"


Recently, while i`m working with javascript i got the following error.

Microsoft JScript runtime error: 'JSON' is undefined

But, It was working in some others system.

Question is Why i got this error ?
After a Little Bit of Googling, i found the reason.
That is, In ie7 or lesser versions native implementation of JSON not supported.
>ie7 have a native implementation of JSON by default. For to use JSON in ie7 or lesser version you need to refer the below js file.

But some time you may get the same error in IE8 or greater versions, in this time you have to check your IE browser rendering in > IE7 standards mode or not. If it is not change to higher version or use the below solution like IE7.

The Solution that works for me was.

Create a script file of below code and call it before JSON object 
called.


var JSON;if(!JSON){JSON={}}(function(){'use strict';function f(n){return n<10?'0'+n:n}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key)}if(typeof rep==='function'){value=rep.call(holder,key,value)}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null'}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null'}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==='string'){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' '}}else if(typeof space==='string'){indent=space}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify')}return str('',{'':value})}}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j}throw new SyntaxError('JSON.parse')}}}());

Source: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

September 22, 2012

Fixed - "Error: A downgrade path is not supported & The Windows Management Instrumentation (WMI) service cannot be started. To continue with the installation, you must troubleshoot and repair your Windows Management Instrumentation (WMI) service."


While trying to publish one of  my application in live environment, i`m getting the following error.

"The database 'E:\blabla\APP_DATA\ASPNETDB.MDF' cannot be opened because it is version 661. This server supports version 612 and earlier. A downgrade path is not supported.
Cannot open user default database. Login failed.
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'."

The Error says you fool, you are using old version of sql instance. To run this MDF you need to update your SQL instance.
So i decide to update my SQL instance from SQL Server 2008 to SQL Server 2008 R2.

while trying to update my server, i got a another error.
"The Windows Management Instrumentation (WMI) service cannot be started. 
To continue with the installation, you must troubleshoot and repair your Windows Management Instrumentation (WMI) service."

It says WMI services need to be run, before starting installation, after some of my hair plugged i find out a solution from a forum.

The solution that works for me was:

1. Copy the below code in a notepad and save it as fixwmi.cmd
2. Run through command promt e.g: type c:\fixwmi.cmd (File location \ filename)
    in command promt and enter.
It takes several minutes to complete, After it is complete, you see the :END statement start the SQL server installation again and you should be fixed.

Code:

@echo on
cd /d c:\temp
if not exist %windir%\system32\wbem goto TryInstall
cd /d %windir%\system32\wbem
net stop winmgmt
winmgmt /kill
if exist Rep_bak rd Rep_bak /s /q
rename Repository Rep_bak
for %%i in (*.dll) do RegSvr32 -s %%i
for %%i in (*.exe) do call :FixSrv %%i
for %%i in (*.mof,*.mfl) do Mofcomp %%i
net start winmgmt
goto End

:FixSrv
if /I (%1) == (wbemcntl.exe) goto SkipSrv
if /I (%1) == (wbemtest.exe) goto SkipSrv
if /I (%1) == (mofcomp.exe) goto SkipSrv
%1 /RegServer

:SkipSrv
goto End

:TryInstall
if not exist wmicore.exe goto End
wmicore /s
net start winmgmt
:End

Jquery - Validate Multiple input controls Inside a Parent

function fnValidateChildFields(parentElement, selector) {
    var isValid = true;
 
    //Get Required Elements inside "Parent Element" By using selector
    //It will return filtered elements.
    var elements = jQuery(parentElement).find(selector);
 
    //For Each all fields and do your stuff
    jQuery.each(elements, function () {
 
        // Do validation Here..
 
        /* SAMPLE VALIDATION STARTS HERE */
 
        alert(this.id);
        alert(this.value);
        alert(this.getAttribute('class'));
 
        // Required Field validation
        if (this.value.length == 0)
            isValid = false;
 
        /* SAMPLE VALIDATION ENDS HERE */
 
    });
 
    return isValid;
}
 
 
function fnValidatePageII() {
    var isValid = false;
    try {
 
        // Parent ID name
        var parentElement = "#divParentID"
 
        // Class Name, It is used to get classes that needs to be replaced.
        var selector = ".className"
 
        if (fnValidateChildFields(parentElement, selector) == true)
            isValid = true;
    }
    catch (e) {
        alert(e);
    }
    return isValid;
}

Jquery - Change/Replace All Css Class Names Inside a Parent

Use the below to change all the class names inside a parent


function replaceCSSClass()
{
    // Parent ID name
    var parentElement = "#divParentID"
 
    // Class Name, It is used to get classes that needs to be replaced.
    var selector= ".className"
 
    //Get All Elements
    var elements = jQuery(parentElement).find(selector);
 
 
    //Here 'oldClassName' is going to be replaced by 'className'
    jQuery.each(elements, function () {
        this.setAttribute
        (
            'class', 
            this.getAttribute('class').replace(/(?:^|\s)oldClassName(?!\S)/g, ' className')
        );
    });
}

C# - Avoid SQL Injection By Validating Strings


What is SQL Injection:
SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution.
By MSDN

For Eg:
Assume the below dynamic query going to execute
String sql = "select * from Products where ProductID = '" + @ProductID + "'";

However, assume a user enters @ProductID as P213445'; drop table Products--

After assembled the above query will be
select * from Products where ProductID = 'P213445'; drop table Products--

This one syntactically correct, if this executes means we lost a table, Right..!!
So We should keep in mind SQL Injection while developing.
We can avoid SQL Injection by several methods, I given one of it.

Use the below one validate user input

//** Doubles up single quotes to stop breakouts from SQL strings **
public static string SQLSafe(string strRawText)
{
    string strCleanedText = "";
    int iCharPos = 0;
 
    while (iCharPos < strRawText.Length)
    {
        //** Double up single quotes, but only if they aren't already doubled **
        if (strRawText.Substring(iCharPos, 1) == "'")
        {
            strCleanedText = strCleanedText + "''";
            if (iCharPos != strRawText.Length)
            {
                if (strRawText.Substring(iCharPos + 1, 1) == "'")
                    iCharPos = iCharPos + 1;
            }
        }
        else
        {
            strCleanedText = strCleanedText + strRawText.Substring(iCharPos, 1);
        }
 
        iCharPos++;
    }
 
    return strCleanedText.Trim();
}

September 10, 2012

SQL SERVER - How to get Master Database File (.mdf) ?

Solution:
SELECT
   NAME
   ,TYPE_DESC
   ,STATE_DESC
   ,PHYSICAL_NAME 'LOCATION'
   ,SIZE
FROM MASTER.SYS.MASTER_FILES
WHERE NAME LIKE '% [ DATABASE NAME ] %'


You will get output like below
NAME        TYPE_DESC    STATE_DESC    LOCATION                                                                  SIZE
-----------------------------------------------------------------------------------------------------------------------
TEST        ROWS         ONLINE        c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\TEST.mdf         280
TEST_log    LOG          ONLINE        c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\TEST_log.LDF     128

2. Go through that resulted location, now you may noticed that, you are unable to copy or move.
     To Copy or Move a file, you need to "detach" required Database from sql server.

3. Copy the required .mdf & .ldf files from the location folder. and attach, file again if it is required.

Fix - "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."


While trying to change something in my project, i got the following error.

"Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."


The below solution that worked for me..

Solution:
Delete all files inside the following folder

C:\Documents and Settings\ USER_NAME \Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS

[ Note: Remember to replace USERNAME with your username. ]

Re-Run the application, That's it.