Tuesday, December 3, 2013

jQuery fast review

Here I have provided some jQuery properties which will give you overview & to quick learn.

While writing jQuery we need to remember two things i.e  
      #"Find element" .. and
      #"do something to it"..
Find element : find a element by selector..
i.e. $("")  --- selector
jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes.

You can select a element by using 
    "element id" using "#"                     -- eg: $("#divid")
    "class attribute" using "." (dot)        -- eg: $(".classname")
    "element tag"  using tag name         -- eg: $("table"), $("div"),..

Examples:
$("#contentid")  -- get element with id "contentid" .
$("li:first")          -- get first list item.
$("tr:odd")         -- get odd numbered table rows
$(this).hide()      -- hides the current element.
$("p").hide()      -- hides all <p> elements.
$(".test").hide()  -- hides all elements with class="test".
$("#test").hide() -- hides the element with id="test".

Properties :
Here are some of properties which are most using..

Hide all div's with jQuery :
$("div").hide( );

You can also find element by string selectors together
$("#myid, .myclass, table")

Add Class:
$("div").addclass("myclass");
here selector find element div and add class attribute "myclass" to it.

jQuery API
Chain method
$("div").addclass("myclass").fadeout();

•Moving Elements:
append(), appendTo(), before(), after(),
•Attributes
css(), attr(), html(), val(), addClass()
•Traversing
find(), is(), prevAll(), next(), hasClass()
•Events
bind(), trigger(), unbind(), live(), click()
•Ajax
get(), getJSON(), post(), ajax(), load()
•Effects
show(), fadeOut(), toggle(), animate()

...post incomplete, updating

Monday, December 2, 2013

Float div position to top when you scroll

In the below code I have explained about Maintaining div tag at top of the screen when scrolling..

IF my current position is greater or equal to the “sticker” position, give the sticker div a class of “stick”.  This changes the CSS of the div to have a FIXED position as long as the viewport is lower than the position of the sticker.





HTML - Take a div tag which contain the data which you want to float.

<div id="sticker">
    ...start scrolling..
   //Add your Code block here...
</div>

CSS 
Styles applied to div#sticker and the class “.stick
"stick" class is most important, which maintain position when you scroll.

div#sticker {
    padding:20px;
    margin:20px 0;
    background:#AAA;
    width:190px;
}
.stick {
    position:fixed;
    top:0px;

}


jQuery – Calculates the position of the sticker div and makes its position fixed if the page has scrolled that far

$(document).ready(function() {
    var s = $("#sticker");
    var pos = s.position();                    
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick"); 
        }

    });

Tuesday, September 24, 2013

Typed and UnTyped Dataset


Untyped dataSet you can created in following manner by creating object of DataSet Class.

Dataset has one table with column name firstName.

DataSet ds = new DataSet();

DataTable dt = new DataTable();

DataColumn one = new DataColumn("FirstName");

dt.Columns.Add(one);

ds.Tables.Add(dt);


You can add typed dataset by following manner,

On Solution Explorer, RightClick -> Add New Item then select DataSet.xsd after that from server explorer you can drag the object or you can manuall also create table. and give "Select Command, InsertCommand , UpdateCommand and DeleteCommand", when you call the method, DataSet.AcceptChanges(); , respective command will be executed based on the Rowstate.

Dynamically Enable or Disable Required Field Validator


To enable or disable the required field validator control based on any selection
Enable or Disable ASP.Net Validation on client side

//Syntax:
ValidatorEnable(ValidatorContronName,Boolean);

//Explanation:
ValidatorContronName - This is ClientID of the Validation control.
Boolean - true(Enable) / false(Disable)

//Example:
rfvOther: is a Required Field Validator
ValidatorEnable(document.getElementById('<%=rfvOther.ClientID%>'), false);


Explonation#2:
'ValidatorEnable' or 'ValidatorUpdateDisplay' will immediately validate the associated control and show any validation messages. If this is not wanted because you just want to toggle the enabled/disabled switch but wait until form submission to validate, then the 2nd method of calling enabled on the object is the preferred method. If you do want immediate validation, then this can be done in a single line of code passing in the ID of the RequiredFieldValidator as displayed below:
ValidatorEnable($get('<%=RequiredFieldValidator1.ClientID %>'), true);
However, if you want only to enable/disable the validator, use the code below and do not make any additional calls to the built in JS functions. The error from previous posts states to set the .enable property yet there is no such thing. You must set the .enabled property on the server control. The code below shows this:
var validator = $get('<%=RequiredFieldValidator1.ClientID %>');
validator.enabled = true;

Monday, September 23, 2013

Difference between DataTable and DataView

Simply, DataView is customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data, but instead represents a connected view of its corresponding DataTable.

when you want to run a query and show the subset of data in a control, a DataView could help you.

DataTable

A datatable is an in-memory representation of a single database table. You can think of it as having columns and rows in the same way. The DataTable is a central object in the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView.

DataView

A dataview is a view on a datatable, a bit like a sql view. It allows you to filter and sort the rows - often for binding to a windows form control.

Additionally, a DataView can be customized to present a subset of data from the DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data. For example, one control may be bound to a DataView showing all of the rows in the table, while a second may be configured to display only the rows that have been deleted from the DataTable. The DataTable also has a DefaultView property which returns the default DataView for the table.

Example:
using(SqlConnection cn = GetConnection())
 {
     cn.Open();
     SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", cn);
     DataTable dt = new DataTable();
     da.Fill(dt);

     // At this point dt is filled with datarows extracted from the database in no particular order 
     // And the DefaultView presents the same record organization (or lack of), but...

     // Order on the default view by CustomerName
     dt.DefaultView.Sort = "CustomerName";
     foreach(DataRowView rv in dt.DefaultView)
          Console.WriteLine(rv["CustomerName"].ToString();

     // A new dataview with only a certain kind of customers ordered by name
     DataView dvSelectedCust = new DataView(dt, "CreditLevel = 1", "CustomerName", DataViewRowState.Unchanged);
     foreach(DataRowView rv in dvSelectedCust)
          Console.WriteLine(rv["CustomerName"],ToString();



 }

Difference between DataView and DataTable
DataView

1.Read-only i.e., DataView can be used to select the data.
2.Is a reference to an existing DataTable. Cannot be populated from scratch; must be instantiated with a reference to an existing DataTable.
3.Data is a reference to an existing DataTable, and does not consume space.
4.Can sort or filter rows without modifying the underlying data. Rows and columns can be hidden and revealed repeatedly.
5.Can return a DataTable version of the view
6.A live reference to a DataTable; any changes in the DataTable data is immediately reflected in the view.
7.Supports calculated columns, which are columns with a value calculated on the fly by combining or manipulating other columns.
8.Can hide or show selected columns

DataTable

1.Read/Write i.e., Datatable can be used to edit or select or delete or insert a data.
2.Can be created empty and then populated
3.Data takes storage space.
4.Can add/edit/delete rows, columns, and data, and all changes are persistent.
5.Can be cloned
6.Is source data; does not contain references
7.Does not support calculated columns
8.No row or column hiding


Thanks,
Reference from Forums,Sites.google,Stackoverflow.

Monday, July 22, 2013

Check if Function Exists Before Calling

When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn't exist. 
you can just check if the function exists before calling it to avoid the error:

Java Script :
if (typeof yourFunctionName == 'function') { yourFunctionName(); }else{ alert('Check yourFunctionName!'); }

Jquery:
Also could be:
$.isFunction(yourFunctionName)&&yourFunctionName()

or if you are sure that if its exists than its a function:
yourFunctionName&&yourFunctionName()

Tuesday, May 14, 2013

An Overview of Classic ASP's Request Object

REF: -- Article from codeguru

The Request Object receives the values that the client's browser passed to the server during an HTTP request.
When you surf to an address that begins with HTTP, the server you're visiting treats that as an "HTTP request"; you are in fact "requesting" that a particular web page is displayed to you. The same applies to any http hyperlinks that you click. A lot more information is being passed back and forth, between your PC and the server of the site you're visiting, than you may be aware of. This chunk of data is called a "request object". Along with the URL you've requested, information about your browser, IP address, the last URL you visited and more is being sent along with your request to view a particular web page. On the flip side, in addition to the web page you requested, the server also sends back server-related information in the same request object.
All this data gets passed in the HTTP request (a.k.a Request Object). Whether it was posted via an online form you filled in ..or.. embedded in the URL as name-value pairs, it all ends up in the Request object. How does that happen, you wonder? That's a helpful feature of Microsoft IIS (internet information services), whereas systems/languages such as Unix/Perl must parse/extract that information manually.
To make life a little simpler, the Request Object has several "collections". A collection is just a fancy word for grouping, segregating or classifying all of the information that's being exchanged. For example, input-capable fields on a form that is sent via "method=post" end up in collection "Form", while name-value pairs sent in the URL (or from a form sent via "method=get") end up in collection "QueryString", etc.
  • ClientCertificate: The values of fields stored in the client certificate that is sent in the HTTP request.
  • Cookies: The values of cookies sent in the HTTP request.
  • Form: The values of form elements in the HTTP request body.
  • QueryString: The values of variables in the HTTP query string.
  • ServerVariables: The values of predetermined server/environment variables.
The syntax is:
     Request[.collection|property|method](variable)
All request object variables can be accessed directly by calling Request(variable) without the collection name. In this case, the Web server searches the collections in the following order:
  1. QueryString
  2. Form
  3. Cookies
  4. ClientCertificate
  5. ServerVariables
If a variable with the same name exists in more than one collection, the Request object returns the first instance encountered. It is strongly recommended that, when referring to members of the ServerVariables collection, the full name be used. For example, rather than Request("AUTH_USER") use Request.ServerVariables("AUTH_USER").

Thursday, April 4, 2013

ASP.NET Web Programming Using the Razor Syntax (C#)

--Article by By Microsoft ASP.NET

Programming Tips



1. You add code to a page using the @ character

The @ character starts inline expressions, single statement blocks, and multi-statement blocks:
<!-- Single statement blocks  -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }
<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
    var greeting = "Welcome to our site!";
    var weekDay = DateTime.Now.DayOfWeek;
    var greetingMessage = greeting + " Today is: " + weekDay;
}<p>The greeting is: @greetingMessage</p>
This is what these statements look like when the page runs in a browser:
Razor-Img1

2. You enclose code blocks in braces

code block includes one or more code statements and is enclosed in braces.
<!-- Single statement block.  -->
@{ var theMonth = DateTime.Now.Month; }<p>The numeric value of the current month: @theMonth</p>
<!-- Multi-statement block. -->
@{
    var outsideTemp = 79;
    var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}<p>Today's weather: @weatherMessage</p>
The result displayed in a browser:
Razor-Img2

3. Inside a block, you end each code statement with a semicolon

Inside a code block, each complete code statement must end with a semicolon. Inline expressions don't end with a semicolon.
<!-- Single-statement block -->
@{ var theMonth = DateTime.Now.Month; }
<!-- Multi-statement block -->
@{
    var outsideTemp = 79;
    var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<!-- Inline expression, so no semicolon -->
<p>Today's weather: @weatherMessage</p>

4. You use variables to store values

You can store values in a variable, including strings, numbers, and dates, etc. You create a new variable using thevar keyword. You can insert variable values directly in a page using @.
<!-- Storing a string -->
@{ var welcomeMessage = "Welcome, new members!"; }<p>@welcomeMessage</p>
<!-- Storing a date -->
@{ var year = DateTime.Now.Year; }
<!-- Displaying a variable -->
<p>Welcome to our new members who joined in @year!</p>
The result displayed in a browser:
Razor-Img3

5. You enclose literal string values in double quotation marks

string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:
@{ var myString = "This is a string literal"; }
If the string that you want to display contains a backslash character (\) or double quotation marks ( " ), use averbatim string literal that's prefixed with the @ operator. (In C#, the \ character has special meaning unless you use a verbatim string literal.)
<!-- Embedding a backslash in a string -->
@{ var myFilePath = @"C:\MyFolder\"; }<p>The path is: @myFilePath</p>
To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:
<!-- Embedding double quotation marks in a string -->
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }<p>@myQuote</p>
Here's the result of using both of these examples in a page:
Razor-Img4

Note   Notice that the @ character is used both to mark verbatim string literals in C# and to mark code in ASP.NET pages. 

6. Code is case sensitive

In C#, keywords (like vartrue, and if) and variable names are case sensitive. The following lines of code create two different variables, lastName and LastName.
@{
    var lastName = "Smith";
    var LastName = "Jones";
}
If you declare a variable as var lastName = "Smith"; and if you try to reference that variable in your page as@LastName, an error results because LastName won't be recognized.

Note   In Visual Basic, keywords and variables are not case sensitive.

7. Much of your coding involves objects

An object represents a thing that you can program with — a page, a text box, a file, an image, a web request, an email message, a customer record (database row), etc. Objects have properties that describe their characteristics and that you can read or change — a text box object has a Text property (among others), a request object has aUrl property, an email message has a From property, and a customer object has a FirstName property. Objects also have methods that are the "verbs" they can perform. Examples include a file object's Save method, an image object's Rotate method, and an email object's Send method.
You'll often work with the Request object, which gives you information like the values of text boxes (form fields) on the page, what type of browser made the request, the URL of the page, the user identity, etc. The following example shows how to access properties of the Request object and how to call the MapPath method of theRequest object, which gives you the absolute path of the page on the server:
<table border="1">
<tr>
    <td>Requested URL</td>
    <td>Relative Path</td>
    <td>Full Path</td>
    <td>HTTP Request Type</td>
</tr>
<tr>
    <td>@Request.Url</td>
    <td>@Request.FilePath</td>
    <td>@Request.MapPath(Request.FilePath)</td>
    <td>@Request.RequestType</td>
</tr>
</table>
The result displayed in a browser:
Razor-Img5

8. You can write code that makes decisions

A key feature of dynamic web pages is that you can determine what to do based on conditions. The most common way to do this is with the if statement (and optional else statement).
@{
   var result = "";
   if(IsPost)
   {
      result = "This page was posted using the Submit button.";
   }
   else
   {
      result = "This was the first request for this page.";
   }
}
<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
<body>
<form method="POST" action="" >
  <input type="Submit" name="Submit" value="Submit"/>
  <p>@result</p>
</form>
</body>
</html>
    </body>
</html>
The statement if(IsPost) is a shorthand way of writing if(IsPost == true). Along with if statements, there are a variety of ways to test conditions, repeat blocks of code, and so on, which are described later in this article.
The result displayed in a browser (after clicking Submit):
Razor-Img6
Razor syntax:

Quick reference about the Razor syntax.
Syntax/SampleRazorWeb Forms Equivalent (or remarks)
Code Block
@{ 
  int x = 123; 
  string y = "because.";
}
<%
  int x = 123; 
  string y = "because."; 
%>
      
Expression (Html Encoded)
<span>@model.Message</span>
<span><%: model.Message %></span>
Expression (Unencoded)
<span>
@Html.Raw(model.Message)
</span>
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
  <span>@item.Prop</span> 
}
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text> 
}
<% if (foo) { %> 
  Plain Text 
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
}
Same as above
Email Addresses
Hi philha@example.com
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
<span>ISBN@(isbnNumber)</span>
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the 
@@foo to display the value 
of foo</span>
@@ renders a single @ in the response.
Server side Comment
@*
This is a server side 
multiline comment 
*@
<%--
This is a server side 
multiline comment
--%>
Calling generic method
@(MyClass.MyMethod<AType>())
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
@{
  Func<dynamic, object> b = 
   @<strong>@item</strong>;
}
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.
NEW IN RAZOR v2.0/ASP.NET MVC 4
Conditional attributes
<div class="@className"></div>
When className = null
<div></div>
When className = ""
<div class=""></div>
When className = "my-class"
<div class="my-class"></div>
Conditional attributes with other literal values
<div class="@className foo bar">
</div>
When className = null
<div class="foo bar"></div>
Notice the leading space in front of foois removed.
When className = "my-class"
<div class="my-class foo bar">
</div>
Conditional data-* attributes.

data-* attributes are always rendered.
<div data-x="@xpos"></div>
When xpos = null or ""
<div data-x=""></div>
When xpos = "42"
<div data-x="42"></div>
Boolean attributes
<input type="checkbox"
  checked="@isChecked" />
When isChecked = true
<input type="checkbox"
  checked="checked" />
When isChecked = false
<input type="checkbox" />
URL Resolution with tilde
<script src="~/myscript.js">
</script>
When the app is at /
<script src="/myscript.js">
</script>
When running in a virtual application named MyApp
<script src="/MyApp/myscript.js">
</script>
Notice in the “mixing expressions and text” example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression.