CheckBox Client side Store in array

No Comments

VIEW DEMO

This is used to add elements in a javascript array on client side. On click of the checkbox it checks if element is not present than adds it into array. On uncheck of checkbox, it removes element from array.

jQuery Prevent navigation by mistake

No Comments

Sometimes a user by mistake presses back button or any link on the page and the data is lost.

Solution: Include this script in your page and also include jquery. Now everytime, user visits this page and makes any form changes than page will prompt message like:“Are you sure, you want to navigate away from this page?”

Very Nice site to learn C#

No Comments

http://www.csharp-examples.net/examples/

Filter your datatable in C#

No Comments

Suppose you run a query on pageload and than store data in a datatable. You then store datatable in viewstate. Now in your page, for all postbacks you use datatable stored in viewstate. Suppose you want to filter the data or rows in the datatable and show it in a grid, than you can use the method discussed here.

NOTE: This won’t change your datatable, it will be the same you had before unless you make changes to datatable and save it.

Example:

DataTable mytbl=GetDataTbl;

DataRow[] rowArray;

string filterexpression = “COL1 LIKE ‘%” + e.Text + “%’ or COL2 LIKE ‘%” + e.Text + “%’”;
rowArray = mytbl.Select(filterexpression);

 

Below written are examples of different expressions that you can use to filter your datatable.

 

DataView RowFilter Syntax [C#]

This example describes syntax of DataView.RowFil­ter expression. It shows how to correctly build expression string (without „SQL injection“) using methods to escape values.

Column names

If a column name contains any of these special characters ~ ( ) # \ / = > < + - * % & | ^ ' " [ ], you must enclose the column name within square brackets [ ]. If a column name contains right bracket ] or backslash \, escape it with backslash (\] or \\).

[C#]

dataView.RowFilter = "id = 10";      // no special character in column name "id"
dataView.RowFilter = "$id = 10";     // no special character in column name "$id"
dataView.RowFilter = "[#id] = 10";   // special character "#" in column name "#id"
dataView.RowFilter = "[[id\]] = 10"; // special characters in column name "[id]"

Literals

String values are enclosed within single quotes ' '. If the string contains single quote ', the quote must be doubled.

[C#]

dataView.RowFilter = "Name = 'John'"        // string value
dataView.RowFilter = "Name = 'John ''A'''"  // string with single quotes "John 'A'"

dataView.RowFilter = String.Format("Name = '{0}'", "John 'A'".Replace("'", "''"));

Number values are not enclosed within any characters. The values should be the same as is the result of int.ToString() or float.ToString() method for invariant or English culture.

[C#]

dataView.RowFilter = "Year = 2008"          // integer value
dataView.RowFilter = "Price = 1199.9"       // float value

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat,
                     "Price = {0}", 1199.9f);

Date values are enclosed within sharp characters # #. The date format is the same as is the result of DateTime.ToString() method for invariant or English culture.

[C#]

dataView.RowFilter = "Date = #12/31/2008#"          // date value (time is 00:00:00)
dataView.RowFilter = "Date = #2008-12-31#"          // also this format is supported
dataView.RowFilter = "Date = #12/31/2008 16:44:58#" // date and time value

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
                     "Date = #{0}#", new DateTime(2008, 12, 31, 16, 44, 58));

Alternatively you can enclose all values within single quotes ' '. It means you can use string values for numbers or date time values. In this case the current culture is used to convert the string to the specific value.

[C#]

dataView.RowFilter = "Date = '12/31/2008 16:44:58'" // if current culture is English
dataView.RowFilter = "Date = '31.12.2008 16:44:58'" // if current culture is German

dataView.RowFilter = "Price = '1199.90'"            // if current culture is English
dataView.RowFilter = "Price = '1199,90'"            // if current culture is German

Comparison operators

Equal, not equal, less, greater operators are used to include only values that suit to a comparison expression. You can use these operators = <> < <= > >=.

Note: String comparison is culture-sensitive, it uses CultureInfo from DataTable.Locale property of related table (dataView.Table.Locale). If the property is not explicitly set, its default value is DataSet.Locale (and its default value is current system culture Thread.Curren­tThread.Curren­tCulture).

[C#]

dataView.RowFilter = "Num = 10"             // number is equal to 10
dataView.RowFilter = "Date < #1/1/2008#"    // date is less than 1/1/2008
dataView.RowFilter = "Name <> 'John'"       // string is not equal to 'John'
dataView.RowFilter = "Name >= 'Jo'"         // string comparison

Operator IN is used to include only values from the list. You can use the operator for all data types, such as numbers or strings.

[C#]

dataView.RowFilter = "Id IN (1, 2, 3)"                    // integer values
dataView.RowFilter = "Price IN (1.0, 9.9, 11.5)"          // float values
dataView.RowFilter = "Name IN ('John', 'Jim', 'Tom')"     // string values
dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values

dataView.RowFilter = "Id NOT IN (1, 2, 3)"  // values not from the list

Operator LIKE is used to include only values that match a pattern with wildcards. Wildcard character is * or %, it can be at the beginning of a pattern '*value', at the end 'value*', or at both '*value*'. Wildcard in the middle of a patern 'va*lue' is not allowed.

[C#]

dataView.RowFilter = "Name LIKE 'j*'"       // values that start with 'j'
dataView.RowFilter = "Name LIKE '%jo%'"     // values that contain 'jo'

dataView.RowFilter = "Name NOT LIKE 'j*'"   // values that don't start with 'j'

If a pattern in a LIKE clause contains any of these special characters * % [ ], those characters must be escaped in brackets [ ] like this [*], [%], [[] or []].

[C#]

dataView.RowFilter = "Name LIKE '[*]*'"     // values that starts with '*'
dataView.RowFilter = "Name LIKE '[[]*'"     // values that starts with '['

The following method escapes a text value for usage in a LIKE clause.

[C#]

public static string EscapeLikeValue(string valueWithoutWildcards)
{
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < valueWithoutWildcards.Length; i++)
  {
    char c = valueWithoutWildcards[i];
    if (c == '*' || c == '%' || c == '[' || c == ']')
      sb.Append("[").Append(c).Append("]");
    else if (c == '\'')
      sb.Append("''");
    else
      sb.Append(c);
  }
  return sb.ToString();
}

[C#]

// select all that starts with the value string (in this case with "*")
string value = "*";
// the dataView.RowFilter will be: "Name LIKE '[*]*'"
dataView.RowFilter = String.Format("Name LIKE '{0}*'", EscapeLikeValue(value));

Boolean operators

Boolean operators AND, OR and NOT are used to concatenate expressions. Operator NOT has precedence over AND operator and it has precedence over OR operator.

[C#]

// operator AND has precedence over OR operator, parenthesis are needed
dataView.RowFilter = "City = 'Tokyo' AND (Age < 20 OR Age > 60)";

// following examples do the same
dataView.RowFilter = "City <> 'Tokyo' AND City <> 'Paris'";
dataView.RowFilter = "NOT City = 'Tokyo' AND NOT City = 'Paris'";
dataView.RowFilter = "NOT (City = 'Tokyo' OR City = 'Paris')";
dataView.RowFilter = "City NOT IN ('Tokyo', 'Paris')";

Arithmetic and string operators

Arithmetic operators are addition +, subtraction -, multiplication *, division / and modulus %.

[C#]

dataView.RowFilter = "MotherAge - Age < 20";   // people with young mother
dataView.RowFilter = "Age % 10 = 0";           // people with decennial birthday

There is also one string operator concatenation +.

Parent-Child Relation Referencing

parent table can be referenced in an expression using parent column name with Parent. prefix. A column in a child table can be referenced using child column name with Child. prefix.

The reference to the child column must be in an aggregate function because child relationships may return multiple rows. For example expression SUM(Child.Price) returns sum of all prices in child table related to the row in parent table.

If a table has more than one child relation, the prefix must contain relation name. For example expression Child(OrdersToItemsRelation).Price references to column Price in child table using relation named OrdersToItemsRe­lation.

Aggregate Functions

There are supported following aggregate functions SUM, COUNT, MIN, MAX, AVG (average), STDEV (statistical standard deviation) and VAR (statistical variance).

This example shows aggregate function performed on a single table.

[C#]

// select people with above-average salary
dataView.RowFilter = "Salary > AVG(Salary)";

Following example shows aggregate functions performed on two tables which have parent-child relation. Suppose there are tables Orders and Items with the parent-child relation.

[C#]

// select orders which have more than 5 items
dataView.RowFilter = "COUNT(Child.IdOrder) > 5";

// select orders which total price (sum of items prices) is greater or equal $500
dataView.RowFilter = "SUM(Child.Price) >= 500";

Functions

There are also supported following functions. Detailed description can be found here DataColumn.Ex­pression.

  • CONVERT – converts particular expression to a specified .NET Framework type
  • LEN – gets the length of a string
  • ISNULL – checks an expression and either returns the checked expression or a replacement value
  • IIF – gets one of two values depending on the result of a logical expression
  • TRIM – removes all leading and trailing blank characters like \r, \n, \t, ‚ ‘
  • SUBSTRING – gets a sub-string of a specified length, starting at a specified point in the string

 

 

100% height and width Layout using jQuery

No Comments

Master Page Client side code:

<%@ Master Language=”C#” AutoEventWireup=”true” CodeFile=”New.master.cs” Inherits=”MasterPages_New” %>

<!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>
<style type=”text/css”>
body,html,form
{
margin:0;
padding:0;
height:100%;
width:100%;
min-width:960px;
}
body
{
overflow:scroll;
}
#main
{
height:100%;
width:100%;
}
#header
{
min-height:50px;
height:50px;
border-bottom:1px solid #91AA44;
/*background-image:url(“ImagesNet/green.jpg”);*/
background-color:Silver;
}
#content
{
height:100%;
width:100%;
margin-top:18px;

}

</style>
<script src=”scripts/jquery-1.7.1.js” type=”text/javascript”></script>
<script type=”text/javascript”>
var browserheight;
var browserwidth;
var contentheight;
$(document).ready(function () {
ManagePageSize();
});

$(window).resize(function () {

ManagePageSize();
});
function ManagePageSize() {
browserheight = $(window).height();
browserwidth = $(window).width();
contentheight = browserheight – $(“#header”).height() – 20;  //2 for border and 10 for margin-top
$(“#content”).css(“height”, contentheight);
$(“body”).css(“width”, browserwidth);
$(“html”).css(“width”, browserwidth);
$(“form”).css(“width”, browserwidth);
}

</script>
<asp:ContentPlaceHolder id=”head” runat=”server”>
</asp:ContentPlaceHolder>
</head>
<body>
<form id=”form1″ runat=”server”>
<div id=”main”>
<div id=”header”>
<h2 style=”color:Maroon;padding-top:10px;margin-top:0px;”> Your Heading </h2>
</div>

<div id=”content”>

<asp:ContentPlaceHolder id=”ContentPlaceHolder2″ runat=”server”>

</asp:ContentPlaceHolder>
</div>

</div>
</form>
</body>
</html>

jQuery Search for HTML Tables

No Comments

You can just include this script and the script automatically places search box on top of all HTML Tables.

NOTE: Search boxes will be placed only on tables with unique ID.

1. Just add the given javascript on your page as reference. Click here to get javascript.

2. Add following lines of script on your page containing HTML Tables.

$(document).ready(function(){

AttachSearchBoxes();

});

View Live Demo

Adding special symbols like copyright and trademarks on html page

No Comments

Suppose you want to add copyright and other special symbols on your web page than you can simply use the HTML reference for them. As an example I have used as below:

Code: <code><p>Copyright Symbol:  &copy;</p></code>

 

Use this link to get entire list of those symbols:

http://www.w3schools.com/tags/ref_entities.asp

Write Server side code on client side

No Comments

Suppose you want to write server side code in client side. Say for example you want to write a for loop to show 10 input checkboxes on a page. You have your <input type=”checkbox” ….> code on client side. Now to include for loop, write your for loop between following delimiters:

<% for(int i=0; i<10; i++)

} %>

<input type=”checkbox” name=”hi” id=”hi”>

<% } %>

See a Demo.

Using C# Properties in ASP.NET

No Comments

Properties get and set values. The C# language provides them as a convenient way to simplify syntax. They are implemented as methods in the intermediate language. They are standard access points to a class from external code.

Unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. Hejlsberg et al., p. 37

Example 1

First, this program introduces an Example class. One field is present and it is used as a backing store for the Number property. The Number property provides get { } and set { } implementations. The get { } implementation must include a return statement. The set { } implementation receives the implicit argument ‘value’, which is the value to which the property is assigned.

Value Keyword

These C# examples show properties. A property is a method that gets or sets a value.

Program that uses public int property [C#]

using System;

class Example
{
    int _number;
    public int Number
    {
	get
	{
	    return this._number;
	}
	set
	{
	    this._number = value;
	}
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Number = 5; // set { }
	Console.WriteLine(example.Number); // get { }
    }
}

Output

5

Main method

Instance property. The Number property is an instance property, which means that the enclosing class Example must first be instantiated before it can be used. The Main method instantiates Example and then uses the Number property setter (example.Number = 5) and getter (example.Number).

Example 2

You can use other types in properties, such as enum types. This example shows the DayOfWeek enum type in a property, which is defined in the System namespace. Also, the example demonstrates how you can insert code in the getter (or setter) that checks the backing store or the parameter value.

DayOfWeek Enum

Program that uses enum property [C#]

using System;

class Example
{
    DayOfWeek _day;
    public DayOfWeek Day
    {
	get
	{
	    // We don't allow this to be used on Friday.
	    if (this._day == DayOfWeek.Friday)
	    {
		throw new Exception("Invalid access");
	    }
	    return this._day;
	}
	set
	{
	    this._day = value;
	}
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Day = DayOfWeek.Monday;
	Console.WriteLine(example.Day == DayOfWeek.Monday);
    }
}

Output

True

Example 3

You can also use the private accessibility modifier on your property setter or getter. In this example, we require that the IsFound property only be set in the Example class domain. We set the IsFound property in the Example constructor. Then, we can only get the property in the Program.Main method.

Program that uses private setter in property [C#]

using System;

class Example
{
    public Example()
    {
	// Set the private property.
	this.IsFound = true;
    }
    bool _found;
    public bool IsFound
    {
	get
	{
	    return this._found;
	}
	private set
	{
	    // Can only be called in this class.
	    this._found = value;
	}
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	Console.WriteLine(example.IsFound);
    }
}

Output

True

Example 4

You can also make an entire property private. If you do this, you can only use the property in the same enclosing class. The Display method in the below example shows how you can use the private property.

Program that uses private property [C#]

using System;

class Example
{
    int _id;
    private int Id
    {
	get
	{
	    return this._id;
	}
	set
	{
	    this._id = value;
	}
    }
    public void Display()
    {
	// Access the private property in this method.
	this.Id = 7;
	Console.WriteLine(this.Id);
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Display();
    }
}

Output

7

Example 5

Properties can also be static, which means they are associated with the type and not an instance of the type. Static classes can only have static properties. Also, this Count property has a side effect that causes the field to be incremented upon each access. Side effects are not usually a good design feature in programs.

Static Modifier Static Class Static Property

Program that uses static property with side effect [C#]

using System;

class Example
{
    static int _count;
    public static int Count
    {
	get
	{
	    // Side effect of this property.
	    _count++;
	    return _count;
	}
    }
}

class Program
{
    static void Main()
    {
	Console.WriteLine(Example.Count);
	Console.WriteLine(Example.Count);
	Console.WriteLine(Example.Count);
    }
}

Output

1
2
3

Omitting the setter. Another interesting thing about this program is that the setter is omitted entirely. It is sometimes useful to omit the setter when you have a property that computes a value entirely in memory or based on other fields or properties only.

Example 6

Another great feature in the C# programming language is called the automatically implemented property. This feature indicates to the C# compiler that a hidden field be generated and used as the backing store. Then, the get and set statements are expanded to use that hidden field.

Program that has automatically implemented property [C#]

using System;

class Example
{
    public int Number
    {
	get;
	set;
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	example.Number = 8;
	example.Number *= 4;
	Console.WriteLine(example.Number);
    }
}

Output

32

Programming tip

Using property in expression. Another interesting tip in this example is that you can use a property getter in an expression. The *= operator is used to multiply the property by itself; this is the same as “example.Number = example.Number * 4″. Because properties are meant to look like fields, this is allowed; obviously methods are not allowed to do this.

Example 7

With automatically implemented properties, you can specify that the getter or setter be private or restricted to some other accessibility domain. This makes it possible to have a private setter and a public getter, which can improve the information hiding in your object model.

Program with automatically implemented property 2 [C#]

using System;

class Example
{
    public Example()
    {
	// Use private setter in the constructor.
	this.Id = new Random().Next();
    }
    public int Id
    {
	get;
	private set;
    }
}

class Program
{
    static void Main()
    {
	Example example = new Example();
	Console.WriteLine(example.Id);
    }
}

Output

2077325073

Note: You cannot omit either the getter or setter in an automatically implemented property. The error reported by the C# compiler reads: “Automatically implemented properties must define both get and set accessors.”

Apply 301 Redirect

No Comments

How Do I Implement a 301 Redirect?

 

A 301 redirect allows visitors and search engines to access a web page after it has been moved. If you have changed the domain name of your web site or changed the file names of pages, then you need to link to the new URLs for visitors and search engine spiders. The 301 permanent redirect is the most search engine-friendly method of redirection to the new URL or page and is the current standard for SEO purposes. Here are instructions on how to code a 301 redirect, depending on your system.

.htaccess 301 Redirect

If the .htaccess file does not exist, create a new file with no trailing extension after the “.htaccess” using a plain text editor (Remember to put the period at the beginning of the file name!). For a Mac, we recommend BBEdit; for Windows, TextPad. Upload it to the root directory of your old web site. Usually that’s in /public_html or /www on your server. *Note: your web server must be a Linux system and have Apache mod_rewrite module enabled.

Add the following to your .htaccess file:

Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://www.new-site.com/$1 [R=301,L]

If you decide to change filenames of individual pages of your site, you can redirect the old URLs to the new URLs by using the following line as an example:

redirect 301 /old_page.html http://www.yourdomain.com/abc/new_page.html

PHP Redirect:

<?
Header( “HTTP/1.1 301 Moved Permanently” );
Header( “Location: http://www.new-domain.com” );
?>

In ASP:

Open the old web page and replace all its content with the following code, replacing “www.new-location.com” with the file name of the new page.

<%@ Language=VBScript %>
<%
Response.Status=”301 Moved Permanently”
Response.AddHeader “Location”, “http://www.new-location.com”
%>

In ASP .NET:

<script runat=”server”>
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = “301 Moved Permanently”;
Response.AddHeader(“Location”,”http://www.new-location.com”);
}
</script>

In IIS (on a Windows server):

1. In internet services manager, right click on the file or folder you wish to redirect.
2. Select “a redirection to a URL”.
3. Enter the redirection page.
4. Check “The exact url entered above”, and the “A permanent redirection for this resource”.
5. Click “Apply”.

web.config 301 redirect

The first example will redirect single pages to a new location. For example, important pages of your site have .htm extensions and you want the new location to be its own directory (IE. http://domain.com/services.htm will change to http://domain.com/services/).

1. Open web.config in the directory where the old pages reside
2. Then add code for the old location path and new destination as follows:

<configuration>
  <location path="services.htm">
    <system.webServer>
      <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
    </system.webServer>
  </location>
  <location path="products.htm">
    <system.webServer>
      <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
    </system.webServer>
  </location>
</configuration>

You may add as many location paths as necessary.

The second example will redirect an entire directory to a new location. For example, if you want http://domain.com/olddir/ redirected to http://domain.com/newdir/ open web.config in /olddir and add the following line of code within the <system.webServer> section:

<httpRedirect enabled="true" destination="http://domain.com/newdir" httpResponseStatus="Permanent" />

In ColdFusion:

Add the following to the ColdFusion page:

<.cfheader statuscode=”301″ statustext=”Moved permanently”>
<.cfheader name=”Location” value=”http://www.new-site.com”>

Canonical Issues – Redirecting non-www to www:

Some webmasters prefer to redirect domain.com to www.domain.com for search engine optimization purposes. The thought is that some incoming links point to their non-www domain and some point to the www domain. So if the domains are consolidated, incoming links are as well. Webmasters who use this redirect usually see instances of search engine rankings with and without the www in their listings and want to consolidate their efforts.

Canonical Redirect using .htaccess

Add the following four lines to your .htaccess file, replacing ‘domain.com’ with your site’s domain. Remember, you need to be hosted on a Linux server with the Apache Mod-rewrite module enabled.

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]

Canonical Redirect using IIS 7.0

For this to work, you need to download and enable the URL Rewrite module for IIS 7. Then the following code is used in the ASP.NET web.config file:

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Redirect to WWW" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^domain.com$" />
          </conditions>
          <action type="Redirect" url="http://www.domain.com/{R:0}"
               redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

 

If you need further help setting up a 301 redirect it is recommended that you contact your web hosting provider. Changes to server configuration should only be made by experienced webmasters. Freshpromo offers the above instructions as a guide and makes no guarantees as to web site performance.

Older Entries