Saturday, May 3, 2014

Display Loading image animation while loading data from server asynchronously using javascript/jquery

 function AjaxCalltoGetResults() {  
   var xmlhttp;  
   var demoval="demo";  
   var responsestring;  
   displayloader("#myLoader"); // < -- Display Loading Animation   
   if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari  
     xmlhttp = new XMLHttpRequest();  
   }  
   else {// code for IE6, IE5  
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
   }  
   xmlhttp.onreadystatechange = function () {  
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {  
       responsestring = xmlhttp.responseText;  
       hideloader("#myLoader");// < -- Hide Loading Animation   
       DemoMethod(responsestring); // < -- Call Any Method or display Results   
     }  
   }  
   xmlhttp.open("GET", "Demopage.aspx?demovar=" + demoval, true);  
   xmlhttp.send();  
 }  
  //pass loader id to display/hide loader  
     function displayloader(loaderid) {  
       $(loaderid).css({  
         height: $(loaderid).parent().height(),  
         width: $(loaderid).parent().width()  
       });  
       $(loaderid).show();  
     }  
     function hideloader(loaderid) {  
       $(loaderid).hide();  
     }  

 //css for image display  
 .ajax-loader {  
   cursor: wait;  
   background:#ffffff url('../img/ajax-loader.gif') no-repeat center center;  
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";  
   filter: alpha(opacity=75);  
   opacity: 0.75;  
   position: absolute;  
   z-index: 10000;  
   display: none;  
 }  

 //put this where you want to display image  
 <div id="myLoader" class="ajax-loader"></div>  

//Image

Thursday, March 6, 2014

Remove SQL Injected Data from Data Column using asp.net c#

 using System;  
 using System.Data;  
 using System.Data.SqlClient;  
 public partial class Check : System.Web.UI.Page  
 {  
   SqlConnection con = new SqlConnection();  
   DataSet ds = new DataSet();  
   SqlDataAdapter adapt;  
   protected void Page_Load(object sender, EventArgs e)  
   {  
     retrievedata("tbltablename", "clmcolumnname");  
     remove("tbltablename", "clmcolumnname");  
   }  
   protected void retrievedata(string tablename, string columnname)  
   {  
     con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;  
     con.Open();  
     string squery = " Select " + columnname + " from " + tablename;  
     adapt = new SqlDataAdapter(squery, con);  
     adapt.Fill(ds);  
     con.Close();  
   }  
   protected void remove(string tablename, string columnname)  
   {  
     using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconn"].ConnectionString))  
     {  
       int colcount = ds.Tables[0].Rows.Count;  
       int j = 0;  
       while (colcount > 0)  
       {  
         string injecteddata= Convert.ToString(ds.Tables[0].Rows[j][0]);  
         if (!injecteddata.IndexOf('<') < 0)  
          {  
           string datapart= "";  
           if (injecteddata.IndexOf('<') > 0)  
           {  
              datapart = injecteddata.Substring(0, injecteddata.IndexOf('<'));  
           }  
           string newqry = "UPDATE " + tablename + " SET " + columnname + "= @datapart WHERE " + columnname + " = @injecteddata";  
           SqlCommand command = new SqlCommand(newqry, connection);  
           command.Parameters.Add("@datapart", SqlDbType.VarChar);  
           command.Parameters["@datapart"].Value = datapart;  
           command.Parameters.Add("@injecteddata", SqlDbType.VarChar);  
           command.Parameters["@injecteddata"].Value = injecteddata;  
           try  
           {  
             connection.Open();  
             Int32 rowsAffected = command.ExecuteNonQuery();             
           }  
           catch (Exception ex)  
           {  
             Console.WriteLine(ex.Message);              
           }  
           finally  
               {  
                 connection.Close();  
               }  
         }  
         j++;  
         colcount--;  
       }  
     }  
   }  
 }  

Sunday, September 22, 2013

Post Data on asp.net Page using Javascript/Jquery


Method : Post

function AjaxCalltoPostData(datastring) {
    var xmlhttp;
    var responsestring;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                  responsestring = xmlhttp.responseText;
         }
    }
    var data = "content=" + datastring;
    xmlhttp.open("POST", "TempPage.aspx", true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);

}

On Page Load of TempPage.aspx Get Data using :
string content = Request["content"];
*******************************************************************************

Method : Get

 function AjaxCallUsingGetMethod() {
        var xmlhttp;
        var responsestring;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {         
                responsestring= xmlhttp.responseText;   
            }
        }
        xmlhttp.open("GET", "TempPage.aspx?func=getdata&source=" + $('#txtsource').val() + "&dest=" + $('#txtdestination').val() + "&fdate=" + $('#datetoday').val() + "", true);
        xmlhttp.send();

    }

On Page Load of TempPage.aspx Get Data using :

  string funname = Convert.ToString(Request.QueryString["func"]);
            if ((funname  + "").Trim().ToLower() == "getdata")
            {
                string src = Convert.ToString(Request.QueryString["source"]);
                string dest = Convert.ToString(Request.QueryString["dest"]);
                DateTime fdate = Convert.ToDateTime(Request.QueryString["fdate"]);
                string xmlres = GetDataFromASPFunc(src, dest, fdate);
                Response.Write(xmlres);
            }

Execute SQL File Using Command Prompt

Execute .sql file using command prompt

sqlcmd -S IPAddress/ServerName -d DatabaseName -i sqlfilepath -U username -P Password

Sample :

sqlcmd -S 127.0.0.1 -d MySampleDB -i C:\TSQL.sql -U mysqluserid -P mypassword


List of Arguments

Sqlcmd
  [-U login id]          [-P password]
  [-S server]            [-H hostname]          [-E trusted connection]
  [-d database name] [-l login timeout]     [-t query timeout]
  [-h headers]           [-s colseparator]      [-w screen width]
  [-a packetsize]        [-e echo input]        [-I Enable Quoted Identifiers]
  [-c cmdend]            [-L[c] list servers[clean output]]
  [-q "cmdline query"]   [-Q "cmdline query" and exit]
  [-m errorlevel]        [-V severitylevel]     [-W remove trailing spaces]
  [-u unicode output]    [-r[0|1] msgs to stderr]
  [-i inputfile]         [-o outputfile]        [-z new password]
  [-f  | i:[,o:]] [-Z new password and exit]
  [-k[1|2] remove[replace] control characters]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-p[1] print statistics[colon format]]
  [-R use client regional setting]
  [-b On error batch abort]
  [-v var = "value"...]  [-A dedicated admin connection]
  [-X[1] disable commands, startup script, environment variables [and exit]]
  [-x disable variable substitution]
  [-? show syntax summary]

Tuesday, June 11, 2013

Quiz using html,css, jquery, xml, javascript

Problem Statement : Build a Single Select quiz engine.  
Technologies: HTML, JavaScript, jQuery, css
1. Load the XML file data.xml.
2. Populate data into a model object.
3. Show first question with options and next button should be disabled.
4. Once user selects an option next button should be enabled.
5. Once all the questions are answered, text on ‘Next’ should change to ‘Show Result’
    and clicking on it should show the result page with total number of questions and number of
    correct answers.



Solution:
 <!DOCTYPE html>  
 <html>  
      <head>  
      <style type="text/css">  
           div#options input{  
                  margin-left: 15px;    
           }  
           ul{  
                   list-style-type: none;  
           }  
           div#wrapper{  
                  width: 500px;    
                  background-color: #FAFAFA;  
                  padding: 10px;  
                  padding-bottom: 35px;  
           }  
           #nextButton{  
                  float:right;  
                  width: 100px;  
                  height: 25px;  
           }  
      </style>  
      <script type="text/javascript" src="js/jquery.min.js"></script>  
      <script type="text/javascript">  
        var nextnodecounter = 0;  
        var xmldocstr;  
        var correctanscounter = 0;  
        var randmarrcnt = 0;  
        var quesindex = 0;  
        var getvalue;  
        var ansarry = new Array();  
        function UITest1() {  
       var xmlhttp;  
       if (window.XMLHttpRequest) {  
         xmlhttp = new XMLHttpRequest();  
       }  
       else {  
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
       }  
       xmlhttp.onreadystatechange = function () {  
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {  
           var dataxml = xmlhttp.responseText;  
           xmldocstr = loadXMLString(dataxml);  
             displaychild(xmldocstr);  
         }  
       }  
       xmlhttp.open("GET", "data.xml", true);  
       xmlhttp.send();  
     }  
   function OnSuccessCall(response) {  
   }  
   function OnErrorCall(response) {  
   }  
   function loadXMLString(str) {  
     if (window.DOMParser) {  
       parser = new DOMParser();  
       xmlDoc = parser.parseFromString(str, "text/xml");  
     }  
     else // Internet Explorer  
     {  
       xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
       xmlDoc.async = "false";  
       xmlDoc.loadXML(txt);  
     }  
     return xmlDoc;  
   }  
   var newxmldoc;  
   function displaychild(newxmldoc) {  
     // randomizeques(newxmldoc);  
     document.getElementById("nextButton").disabled = true;  
     if (document.getElementById("nextButton").innerHTML == "Show Result") {  
       document.getElementById("nextButton").disabled = false;  
       document.getElementById("nextButton").onclick=ShowResult();  
     }  
     var questiontext = newxmldoc.getElementsByTagName("question");  
     var nodevalue1 = newxmldoc.getElementsByTagName("question_text")[nextnodecounter].childNodes[0].nodeValue;  
     // display question text  
     document.getElementById("question").innerHTML = nodevalue1;  
     document.getElementById("options").innerHTML = "";  
     var answer = newxmldoc.getElementsByTagName("question_text");  
     var optiontext = newxmldoc.getElementsByTagName("option");  
     for (var anscount = 0; anscount < questiontext.length; anscount++) {  
       var indexofans= answer[anscount].getAttribute("answer");  
       ansarry[anscount] = questiontext[nextnodecounter].getElementsByTagName("option")[indexofans - 1].textContent;  
     }  
     //display radio buttons  
     for (i = 0; i < optiontext.length; i++) {  
       //var nodevalue2 = "" + newxmldoc.getElementsByTagName("option")[i].childNodes[0].nodeValue;  
       var nodevalue2 = questiontext[nextnodecounter].getElementsByTagName("option")[i].textContent;  
       var radioBtn = $('<li><input name="r1" type="radio" value="' + nodevalue2 + '" onclick="enablebtn(this.value)" id="rbtnCount" ' + i + ' /><label>' + nodevalue2 + '</label> </li>');  
       radioBtn.appendTo('#options');  
       checkradiobtn();  
     }  
   }  
   function FunNextNode() {  
     nextnodecounter = nextnodecounter + 1;  
     $("#wrapper").animate({ height: '0px', opacity: '0.5' }, "fast");  
     $("#wrapper").promise().done(function () {  
     });  
     $("#wrapper").animate({ height: '150px', opacity: '1' }, "slow");  
     $("#wrapper").promise().done(function () {  
     });  
     if (getvalue == ansarry[nextnodecounter]) {  
       correctanscounter = correctanscounter + 1;  
     }  
     var questiontext = xmldocstr.getElementsByTagName("question");   
     if (questiontext.length == (nextnodecounter)) {  
       document.getElementById("nextButton").innerHTML = "Show Result";  
     }  
       displaychild(xmldocstr);  
   }  
   function checkradiobtn()  
   {  
     var radios = document.getElementsByTagName('input');  
     var value;  
     for (var i = 0; i < radios.length; i++) {  
       if (radios[i].type == 'radio' && radios[i].checked) {  
         document.getElementById("nextButton").disabled = true;  
       }  
     }  
   }  
   var setvalue;  
   function enablebtn(setvalue) {  
     document.getElementById("nextButton").disabled = false;  
     getvalue = setvalue;  
   }  
   function ShowResult() {  
     if (getvalue == ansarry[nextnodecounter-1]) {  
       correctanscounter = correctanscounter + 1;  
     }  
     document.getElementById("result").style.display="block";  
     document.getElementById("noofques").innerHTML = nextnodecounter;  
     document.getElementById("noofcorans").innerHTML = correctanscounter;  
   }  
   // function to get random index of questions  
   var tempcount = 0;  
   var tempxmldoc;  
   var randquearr = new Array();  
   function randomizeques(tempxmldoc) {  
     var questiontext = tempxmldoc.getElementsByTagName("question");  
     var randomno = Math.floor((Math.random() * questiontext.length) + 1);  
     var tempnodevalue = tempxmldoc.getElementsByTagName("question_text")[randomno].childNodes[0].nodeValue;  
     if (tempcount == 0) {  
       randquearr[randmarrcnt] = tempnodevalue;  
       tempcount = tempcount + 1;  
       randmarrcnt = randmarrcnt + 1;  
     }  
     else {  
       for (var tempcnt = 0; tempcnt < randquearr.length; tempcnt++) {  
         if (randquearr[tempcnt] == tempnodevalue) {  
           randomizeques(tempxmldoc);  
         }  
       }  
       randquearr[randmarrcnt] = tempnodevalue;  
       randmarrcnt = randmarrcnt + 1;  
     }  
     quesindex = randomno;  
   }  
      </script>  
      </head>  
      <body onload="UITest1()">  
           <div id="wrapper">  
                  <div id="question">  
                  </div>  
         <br />  
                  <ul id="options">  
                  </ul>  
                  <button id="nextButton" onclick="FunNextNode()">Next</button>  
           </div>  
     <br />  
     <center>  
     <div id="result" style="display:none;height:200px;width:500px;background-color:rgb(152, 173, 240)">  
   &nbsp;&nbsp;&nbsp; No of Questions : <div id="noofques"></div><br />  
   &nbsp;&nbsp;&nbsp; No of Correct Answers : <div id="noofcorans"></div>  
     </div></center>  
      </body>  
 </html>  

XML
 <questions>  
      <question>  
           <question_text answer="1">Question 1</question_text>  
           <options>  
                <option>Option 1</option>  
                <option>Option 2</option>  
                <option>Option 3</option>  
           </options>  
      </question>  
      <question>  
           <question_text answer="1">Question 2</question_text>  
           <options>  
                <option>Option 1</option>  
                <option>Option 2</option>  
                <option>Option 3</option>  
                <option>Option 4</option>  
           </options>  
      </question>  
      <question>  
           <question_text answer="1">Question 3</question_text>  
           <options>  
                <option>Option 1</option>  
                <option>Option 2</option>  
           </options>  
      </question>  
 </questions>  





Thursday, May 9, 2013

Calling ASP.net code behind Methods from javascript


Javascript function

        function callme() {
         
            var str = '<%=GetString()%>';
            alert(str);
        }
function ClickAspbtnfromjavacript() //function for clicking asp.net button from javascript
{
 document.getElementById('btnID').click();
}
 
ASP.net (.aspx page)

body onload="callme()"

Code Behind(.cs page)


 public string GetString()
    {  
        return "Testing";
    }

Disable Previous Dates in Ajax Calendar Control in asp.net
  CalendarExtender1.StartDate = System.DateTime.Today;