Sunday, March 31, 2013

jQuery Modal popup : Misc Basics : dialog("open") and button click open


1. Opening a modal pop-up on button click

 a.    $(function() {
        $("#mybtn").click(function() {
            $("#mydlg").dialog();
        });
    });

OR
 b.        $(document).ready(function() {
            $("#mybtn").click(function() {
                $("#mydlg").dialog();
            });
        });

Both of these will work.

Full code :
<head runat="server">
    <title></title>
    <script src="jquery-1.9.1.js" type="text/javascript"></script>
    <link href="jquery-1.10.2-ui.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.10.2-ui.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#mybtn").click(function() {
                $("#mydlg").dialog();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="mydlg">
   
    </div>
    <button type="button" id="mybtn"></button>
    </form>
</body>





=================================================
2. Using dialog("open")

To enable dialog("open"), you should disable the dialog's autoOpen behavior:

<script type="text/javascript">
    $(document).ready(function() {
        $("#mydlg").dialog({ autoOpen: false });
        $("#mybtn").click(function() {
            $("#mydlg").dialog("open");
        });
    });
</script>


Full Code :
<head runat="server">
    <title></title>
    <script src="jquery-1.9.1.js" type="text/javascript"></script>
    <link href="jquery-1.10.2-ui.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.10.2-ui.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#mydlg").dialog({ autoOpen: false });
        $("#mybtn").click(function() {
            $("#mydlg").dialog("open");
        });
    });
</script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div id="mydlg">
    </div>
    <input type="button" id="mybtn" />
    </form>
</body>
=============================================================


jQuery Modal Popups : Adding Ok, Cancel buttons

We need to add Ok, Cancel etc like any other buttons on the modal pop-up : just add them to the buttons array.


buttons: {
                    Ok: function() { alert("you pressed ok"); },
                    Cancel: function() { alert("you pressed cancel"); },
                    Close: function() { alert("Closing the dialog!"); $(this).dialog("close"); }
}

Full Code:



<head runat="server">
    <title></title>
    <script src="jquery-1.9.1.js" type="text/javascript"></script>
    <script src="jquery-1.10.2-ui.js" type="text/javascript"></script>
    <link href="jquery-1.10.2-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function() {
            $("#mydlg").dialog(
            {
                buttons: {
                    Ok: function() { alert("you pressed ok"); },
                    Cancel: function() { alert("you pressed cancel"); },
                    Close: function() { alert("Closing the dialog!"); $(this).dialog("close"); }
                }
            }
            );
            $("#mybtn").click(function() {
                $("#mydlg").dialog();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="mydlg">
    </div>
    <button type="button" id="mybtn">
    </button>
    </form>
</body>

HTML input and button

HTML input is older, but button is newer, so some old browser versions did not support button, consequently some people advise to use input rather than button.

button supports only three types : button, submit, reset
where as the older counterpart supports 10 types in html 4.01 and around 20 in html 5


For button, different browsers support different default types, where as for input the default type is text.
For IE, default type is submit.

So when you are using button without specifying type, be aware that it might be submit, and it will case a post. This might be a problem when submit behavior is not intended,e.g. you want to do something else ( calculate some value on the form itself) on a button press.

So keep in mind that <button> and <input type="button"> may not be always equivalent, but
<button type="button"> and <input type="button"> are equivalent.


If fact you should know that :
1. button type=“submit” is the same as input type=“submit”
2. button type=“reset” is the same as input type=“reset”
3. button type=“button” is the same as input type=“button”

For a very good explanation on this topic, see : http://nickcowie.com/presentation/s5-button.html

What are the types supported by the HTML input tag ?


What are the types supported by the HTML input tag ?

There are 10 such types :


text
submit
reset
passowrd
radio
button
checkbox
file
hidden
image


HTML 5 now supports additional input types :

color
date
datetime
datetime-local
email
month
number
range
search
tel
time
url
week

jQuery Learnings : sequence of including script files is important


Sequence of js :
while putting the <script> tags for jQuery js files, keep in minds the hierarchy; e.g. ui should come after jquery.

The following will not work :

    <link href="jquery-1.10.2-ui.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.10.2-ui.js" type="text/javascript"></script>
    <script src="jquery-1.9.1.js" type="text/javascript"></script>


Whereas the following will work:

    <script src="jquery-1.9.1.js" type="text/javascript"></script>
    <link href="jquery-1.10.2-ui.css" rel="stylesheet" type="text/css" />
    <script src="jquery-1.10.2-ui.js" type="text/javascript"></script>




This also negates the earlier post that we need to preserve the file names exactly. (http://rschandrastechblog.blogspot.in/2013/03/learnings-of-jquery-basic-modal-dialog.html)There might have been another error earlier.

Learnings of the jQuery Basic Modal Dialog


1. Following three files are required for correct working of jQuery Modal Dialog :
jquery-1.9.1.js
jquery-ui.css
jquery-ui.js

2. Do not rename any of the above files while downloading ( especially the last two files), because they may be refering each other by exact names and renaming them causes the app  not to work.
(Update : This may not be true, please refer to another post about jQuery modal on this date itself. http://rschandrastechblog.blogspot.in/2013/03/jquery-learnings-sequence-of-including.html)

3. A direct call to .dialog will not work, it must be wrapped in some jQuery func, at least $(function(){});

e.g the following will not work :

<head runat="server">
    <script src="jquery-1.9.1.js" type="text/javascript"></script>
    <link href="jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="jquery-ui.js" type="text/javascript"></script>
    <script type="text/javascript">
     $("#dlg").dialog();
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="dlg">
    </div>
    </form>
</body>

But the following will work, because $("dlg).dialog is wrapped in a jQuery function() :

Friday, March 29, 2013

Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

One of my new comer collegue encountered this when he was trying to add a new row to a datatable bound to a GridView and trying to put the new row in edit mode. The error was pretty confusing and bewildering for a new comer :


Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.


We, the somewhat experienced people are used to such errors and ignore them as a part of our life, but the new comers are not used to it! 

The notorious error is thrown when somebody rebinds data to a GridView in Page_Load, without PostBack check. A postback check like the following solved the error  in the Page_Load: 

            if (!Page.IsPostBack){
                          GridView1.DataSource = dt;
                          GridView1.DataBind();
                          }

Thursday, March 28, 2013

How to generate from GridView ?




http://www.dotnetcurry.com/ShowArticle.aspx?ID=250
In order to prevent the Column Header to be highlighted, use the following code to generate the <thead>:
C#
if (GridView1.Rows.Count > 0)
{
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
//GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
}
VB.NET
If GridView1.Rows.Count > 0 Then
GridView1.UseAccessibleHeader = True
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader
'GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
End If
The code above generates the <thead> tag for us instead of generating the <th> in the <tr> (which is the default html generated). I have on purpose commented out the FooterRow code, since it gives me a strange error. I have used a second approach to solve that to a certain extent. Read on.


OdeToCode : Table Variables In T-SQL


ttp://odetocode.com/articles/365.aspx

Table Variables In T-SQL

Monday, March 21, 2005
·         Tweet
·          
·          
Microsoft introduced table variables with SQL Server 2000 as an alternative to using temporary tables. In many cases a table variable can outperform a solution using a temporary table, although we will need to review the strengths and weaknesses of each in this article.
Table variables store a set of records, so naturally the declaration syntax looks very similar to a CREATE TABLE statement, as you can see in the following example:
DECLARE @ProductTotals TABLE
(
ProductID int,
Revenue money
)
While connected to the Northwind data-base, we could write the following SELECT statement to populate the table variable.
INSERT INTO @ProductTotals (ProductID, Revenue)
SELECT ProductID, SUM(UnitPrice * Quantity)
FROM [Order Details]
GROUP BY ProductID
You can use table variables in batches, stored procedures, and user-defined functions (UDFs). We can UPDATE records in our table variable as well as DELETE records.
UPDATE @ProductTotals
SET Revenue = Revenue * 1.15
WHERE ProductID = 62
DELETE FROM @ProductTotals
WHERE ProductID = 60
SELECT TOP 5 *
FROM @ProductTotals
ORDER BY Revenue DESC
You might think table variables work just like temporary tables (CREATE TABLE #ProductTotals), but there are some differences.

Scope

Unlike the majority of the other data types in SQL Server, you cannot use a table variable as an input or an output parameter. In fact, a table variable is scoped to the stored procedure, batch, or user-defined function just like any local variable you create with a DECLARE statement. The variable will no longer exist after the procedure exits - there will be no table to clean up with a DROP statement.
Although you cannot use a table variable as an input or output parameter, you can return a table variable from a user-defined function – we will see an example later in this article. However, because you can’t pass a table variable to another stored procedure as input – there still are scenarios where you’ll be required to use a temporary table when using calling stored procedures from inside other stored procedures and sharing table results.
The restricted scope of a table variable gives SQL Server some liberty to perform optimizations.

Performance

Because of the well-defined scope, a table variable will generally use fewer resources than a temporary table. Transactions touching table variables only last for the duration of the update on the table variable, so there is less locking and logging overhead.
Using a temporary table inside of a stored procedure may result in additional re-compilations of the stored procedure. Table variables can often avoid this recompilation hit. For more information on why stored procedures may recompile, look at Microsoft knowledge base article 243586 (INF: Troubleshooting Stored Procedure Recompilation).

Other Features

Constraints are an excellent way to ensure the data in a table meets specific requirements, and you can use constraints with table variables. The following example ensures ProductID values in the table will be unique, and all prices are less then 10.0.
DECLARE @MyTable TABLE
(
ProductID int UNIQUE,
Price money CHECK(Price < 10.0)
)
You can also declare primary keys. identity columns, and default values.
DECLARE @MyTable TABLE
(
ProductID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(10) NOT NULL DEFAULT('Unknown')
)
So far it seems that table variables can do anything temporary tables can do within the scope of a stored procedure, batch, or UDF), but there are some drawbacks.

Restrictions

You cannot create a non-clustered index on a table variable, unless the index is a side effect of a PRIMARY KEY or UNIQUE constraint on the table (SQL Server enforces any UNIQUE or PRIMARY KEY constraints using an index).
Also, SQL Server does not maintain statistics on a table variable, and statistics are used heavily by the query optimizer to determine the best method to execute a query. Neither of these restrictions should be a problem, however, as table variables generally exist for a specific purpose and aren’t used for a wide range of ad-hoc queries.
The table definition of a table variable cannot change after the DECLARE statement. Any ALTER TABLE query attempting to alter a table variable will fail with a syntax error. Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries. f you are using a table variable in a join, you will need to alias the table in order to execute the query.
SELECT ProductName, Revenue
FROM Products P
INNER JOIN @ProductTotals PT ON P.ProductID = PT.ProductID
You can use a table variable with dynamic SQL, but you must declare the table inside the dynamic SQL itself. The following query will fail with the error “Must declare the variable '@MyTable'.”
DECLARE @MyTable TABLE
(
ProductID int ,
Name varchar(10)
)
EXEC sp_executesql N'SELECT * FROM @MyTable'
It’s also important to note how table variables do not participate in transaction rollbacks. Although this can be a performance benefit, it can also catch you off guard if you are not aware of the behavior. To demonstrate, the following query batch will return a count of 77 records even though the INSERT took place inside a transaction with ROLLBACK.
DECLARE @ProductTotals TABLE
(
ProductID int ,
Revenue money
)
BEGIN TRANSACTION
INSERT INTO @ProductTotals (ProductID, Revenue)
SELECT ProductID, SUM(UnitPrice * Quantity)
FROM [Order Details]
GROUP BY ProductID
ROLLBACK TRANSACTION
SELECT COUNT(*) FROM @ProductTotals

Choosing Between Temporary Tables and Table Variables

Now you’ve come to a stored procedure that needs temporary resultset storage. Knowing what we have learned so far, how do you decide on using a table variable or a temporary table?
First, we know there are situations that which demand the use of a temporary table. This in-cludes calling nested stored procedures which use the resultset, certain scenarios using dy-namic SQL, and cases where you need transaction rollback support.
Secondly, the size of the resultset will determine which solution to choose. If the table stores a resultset so large you require indexes to improve query performance, you’ll need to stick to a temporary table. In some borderline cases try some performance benchmark testing to see which approach offers the best performance. If the resultset is small, the table variable is always the optimum choice.

An Example: Split

Table variables are a superior alternative to using temporary tables in many situations. The ability to use a table variable as the return value of a UDF is one of the best uses of table vari-ables. In the following sample, we will address a common need: a function to parse a delimited string into pieces. In other words, given the string “1,5,9” – we will want to return a table with a record for each value: 1, 5, and 9.
The following user-defined function will walk through an incoming string and parse out the individual entries. The UDF insert the en-tries into a table variable and returns the table variable as a result. As an example, calling the UDF with the following SELECT statement:
SELECT * FROM fn_Split('foo,bar,widget', ',')
will return the following result set.
position value
1              foo
2              bar
3              widget
We could use the resultset in another stored procedure or batch as a table to select against or filter with. We will see why the split function can be useful in the next OdeToCode article. For now, here is the source code to fn_Split.
if exists (select * from dbo.sysobjects where id = ob-ject_id(N'[dbo].[fn_Split]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_Split]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION fn_Split(@text varchar(8000), @delimiter varchar(20) = ' ')
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE @index int
SET @index = -1
WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

Summary

Next time you find yourself using a temporary table, think of table variables instead. Table variables can offer performance benefits and flexibility when compared to temporary tables, and you can let the server clean up afterwards.

jQuery Misc



jQuery :



how do you write the $(document) funcion call ?

$('document').loaded()
$(document).onload()
$(document).onready()
$(document).ready()
$("document).ready()

$(document).ready() is the correct option


detach,remove and replaceWith

Difference in detach and remove : detach keeps the removed item around so that it can be reattached.
remove altogether removes the item
replaceWith : removes the earlier content and inserts new in its place


what is jQuery animation ?
jQuery animation is achieved by using jQuery.animate function. The functions takes a css property , duration, easing and completion callback

property - any valid css property like height, width, color etc.
duration - duration in milliseconds
easing - swing  or linear
completion - completion callback





what is the difference in window and document ?

window is viewable area of the browser
document is the entire HTML document.

So when there is a vertical scrollbar, document has more height that window.

document is also available as window.document.
document contains entire DOM elements
getElementByName/getElementById is supported by document, not by window





gridview hovering sample
        $(document).ready(function() {
        $("#<%=GridView1.ClientID%> ").hover(
            function() {
                $(this).css("background-color", "red");
            },
            function() {
                $(this).css("background-color", "blue");
            }
           
            );
        });

jQuery and GridView : How to highlight current cells column and row

We do not have any direct functionality : so every time on hover of a cell, [I] we will color whole grid with default ( no highlight) color [II] then we will highlight current row [III] then we will highlight current column.

GridView cell ("tr td") will be our base for all these actions.

jQuery closest() and prevAll will play a very important role in deriving current row and column index.




       $(document).ready(function() { //document start
            $("#<%=GridView1.ClientID%> tr td").hover( /*hover start*/
        function()  /*func1*/{ /*$(this).css("background-color","red");*/
            var colindex = $(this).closest("tr td").prevAll("tr td").length;
            var rowindex = $(this).closest("tr").prevAll("tr").length;
            $(document).find("#<%=mlabel.ClientID%>").text(colindex + ' ' + rowindex);
           
            /* color all the grid with default background - this is necessary to erase earlier effects */
            $("#<%=GridView1.ClientID%> tr td").each(function() { $(this).css("background-color", "blue"); });
            /* color this row with highlight color - note we are taking tr here, then going to each td and coloring it. somehow coloring full tr is not workig, possibly because we are hovering over "tr td" and not "tr" */
            $("#<%=GridView1.ClientID%> tr").eq(rowindex).find("td").css("background-color", "red");            
            /* color this column - the technique is to color nth col of each row , iteratively */
            $("#<%=GridView1.ClientID%> tr").each(function() { $(this).find("td").eq(colindex).css("background-color", "red"); });
        }, /* func1*/
       
         /* func2  - this has almost no role*/
        function() { $(this).css("background-color", "blue"); }
        /* func2 */      
       
            /*hover end*/);


         
        });     //document end

jQuery : How to find row and column index of a GridView Cell

on the hover function of (" tr td") :


            var colindex = $(this).closest("tr td").prevAll("tr td").length;
            var rowindex = $(this).closest("tr").prevAll("tr").length;


Here is the complete function :


 $(document).ready(function() {
            $("#<%=GridView1.ClientID%> tr td").hover(
        function()  {
            var colindex = $(this).closest("tr td").prevAll("tr td").length;
            var rowindex = $(this).closest("tr").prevAll("tr").length;
/* mlabel is an asp.net label on which we will display col and row index of current GridView cell
            $(document).find("#<%=mlabel.ClientID%>").text(colindex + ' ' + rowindex);
        },
       
        function() { $(this).css("background-color", "blue"); }
       
        );
        });



$("#<%=GridView1.ClientID%> tr td") indicates one GridView cell.

Wednesday, March 27, 2013

Difference in eq() and :eq() : becomes significant in case nested div


below : first eq(4) gives 4 div ( including the outer one), where as :eq(4) gives fourth INNER div
this needs to be investigated.




<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="eq.aspx.cs" Inherits="_Default" %>

<!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></title>
    <script language="javascript" src="jquery-1.7.2.min.js" type="text/javascript" ></script>
    <script type="text/javascript">
        $(document).ready(
        function() {
        $("div").eq(4).click(function() { alert("789"); });
        $("div :eq(4)").click(function() { alert("000"); });
        }
        );
       
    </script>
</head>
<body>
    <form id="form1" runat="server">
<div>
    <div>aaa</div>
    <div>bbb</div>
    <div>ccc</div>
    <div>ddd</div>
    <div>eee</div>
</div>
<script type="text/javascript">
    $("div").eq(2).click(function() { alert("123"); });
    $("div :eq(2)").click(function() { alert("456"); });
    </script>
    </form>
</body>
</html>

two ways of using jQuery eq() selector : note that eq selector is not there in CSS, it is a javascript extension. eq() method call is perfwise better in modern browsers



eq() selector is not a part of CSS specification
for better performance in modern browsers, use .eq() method instead.



<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){

  $("div:eq(1)").click(function(){alert("qqq");});
  $("div").eq(3).click(function(){alert("www");});
});
</script>
</head>
<body>
<div>aaa</div>
<div>bbb</div>
<div>ccc</div>
<div>ddd</div>
<div>eee</div>
<div>Messages will be displayed on clicking bbb,ddd, and eee above</div>
<script>
$("div").eq(4).click(function(){alert("vvv");});
</script>
</body>
</html>

jQuery difference between questions


Difference between two dates
append and after
click and live
append and appendto
live and bind
offset and position
prop and attr
html and append
remove and hide

Tuesday, March 26, 2013

jQuery animation


<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({left:'250px'},5000);
$("div").animate({right:'250px'},5000);
    $("div").animate({backgroundColor: "#aa0000",
          color: "#cff",
          width: 500},5000);
$("div").text = "aaa";
   $("div").animate({backgroundColor: "#aa0000",
          color: "#fff",
          width: 100},5000);
  });
});
</script>
</head>

<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>

</body>
</html>

How to get or set the value of controls through jQuery




How to get or set the value of controls through jQuery

from w3schools : 

Get Content - text(), html(), and val()

Three simple, but useful, jQuery methods for DOM manipulation are:
  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields

jQuery : making a button draggable : use draggable({cancel:false})









<!DOCTYPE html>
<html>
<head>
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
 <script>
  $(function() {
$("#mydiv").draggable();
$("#mybutton").draggable({cancel:false});
  });
  </script>
</head>
<body>

<div id="mydiv" > sdfdsfds </div>
<input type="button" id="mybutton" value="Submit form" />
</body>
</html>

Sunday, March 17, 2013


Good list of cloud computing learning


This is list from http://weblogs.asp.net/sbehera/archive/2011/11/18/good-list-of-cloud-computing-learning.aspx