Here you will find about .net technology. also can get example about MVC.net and jquery.
Saturday, October 5, 2013
Friday, September 27, 2013
Set Expiration Values for ASP.NET Page Caching
c#
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
vb
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)) Response.Cache.SetCacheability(HttpCacheability.Public) Response.Cache.SetValidUntilExpires(True)
very useful htaccess tips & tricks
Apache web servers has a great way to manipulate information using .htaccess files. .htaccess (hypertext access) is the default name of a directory-level configuration file that allows for decentralized management of web server configuration. The .htaccess file is placed inside the web tree, and is able to override a subset of the server’s global configuration; the extent of this subset is defined by the web server administrator. The original purpose of .htaccess was to allow per-directory access control (e.g. requiring a password to access the content), hence the name. Nowadays .htaccess can override many other configuration settings, mostly related to content control, e.g. content type and character set, CGI handlers, etc.
Following are few very useful htaccess tricks.1. Custom Directory Index Files
DirectoryIndex index.html index.php index.htm |
2. Custom Error Pages
ErrorDocument 404 errors/404.html |
ErrorDocument 404 /psych/cgi-bin/error/error?404 |
3. Control access at files & directory level
.htaccess is most often used to restrict or deny access to individual files and folders. A typical example would be an “includes” folder. Your site’s pages can call these included scripts all they like, but you don’t want users accessing these files directly, over the web. In that case you would drop an .htaccess file in the includes folder with content something like this.# no one gets in here! deny from all |
# no nasty crackers in here! order deny,allow deny from all allow from 192.168.0.0/24 # this would do the same thing.. #allow from 192.168.0 |
Sometimes, you will only want to ban one IP, perhaps some persistent robot that doesn’t play by the rules.
# someone else giving the ruskies a bad name.. order allow,deny deny from 83.222.23.219 allow from all |
4. Modifying the Environment Variable
Environment variables contain information used by server-side includes and CGI. Set / Unset environment variables using SetEnv and UnSetEnv.SetEnv SITE_WEBMASTER "Jack Sprat" SetEnv SITE_WEBMASTER_URI mailto:Jack.Sprat@characterology.com UnSetEnv REMOTE_ADDR |
5. 301 Redirect using htaccess
If you want to redirect from an old document to new:Redirect 301 /old/file.html http://yourdomain.com/new/file.html |
RedirectMatch 301 /blog(.*) http://yourdomain.com/$1 |
6. Implementing a Caching Scheme with .htaccess
Cache the static files and improve your website’s performance.# year < FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$"> Header set Cache-Control "public" Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT" Header unset Last-Modified </ FilesMatch > #2 hours < FilesMatch "\.(html|htm|xml|txt|xsl)$"> Header set Cache-Control "max-age=7200, must-revalidate" </ FilesMatch > < FilesMatch "\.(js|css)$"> SetOutputFilter DEFLATE Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT" </ FilesMatch > |
7. Compress output using GZIP
Add following snippet into your htaccess file and compress all the css, js, html files with GZip compression.< IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </ IfModule > |
< Location > SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png)$ no-gzip dont-vary SetEnvIfNoCase Request_URI \ \.(?:exe|t?gz|zip|gz2|sit|rar)$ no-gzip dont-vary </ Location > |
< FilesMatch "\.(txt|html|htm|php)"> php_value output_handler ob_gzhandler </ FilesMatch > |
8. Redirect browser to https (ssl)
Add following snippet to your htaccess and redirect entire website to https.RewriteEngine On RewriteCond %{HTTPS} !on RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} |
9. Rewrite URLs using htacccess
Rewriting product.php?id=12 to product-12.htmlRewriteEngine on RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1 |
RewriteEngine on RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2 |
RewriteEngine On RewriteCond %{HTTP_HOST} ^viralpatel\.net$ RewriteRule (.*) http://www.viralpatel.net/$1 [R=301,L] |
RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1 RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1 |
RewriteEngine On RewriteCond %{HTTP_HOST} ^test\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.test\.com$ RewriteCond %{REQUEST_URI} !^/new/ RewriteRule (.*) /new/$1 |
10. Prevent Directory Listing
Add any of the following snippet to avoid directory listing.Options -Indexes |
IndexIgnore * |
11. Adding new MIME types
The type of file depends on the filename extension. Unrecognized file extensions are treated as text data, and corrupted on download.AddType application/x-endnote-connection enz AddType application/x-endnote-filter enf AddType application/x-spss-savefile sav |
12. Deny access to static file data
Denies any request for static files (images, css, etc) if referrer is not local site or empty.RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC] RewriteCond %{HTTP_REFERER} !^http://www.askapache.com.*$ [NC] RewriteRule \.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$ - [F,NS,L] |
13. Specify Upload file limit for PHP in htaccess
php_value upload_max_filesize 20M php_value post_max_size 20M php_value max_execution_time 200 php_value max_input_time 200 |
14. Disallow Script Execution
Options -ExecCGI AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi |
15. Change Charset and Language headers
AddDefaultCharset UTF-8 DefaultLanguage en-US |
16. Set Timezone of the Server (GMT)
SetEnv TZ America/Indianapolis |
17. Force “File Save As” Prompt
AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4 |
18. Protecting a single file
Normally .htaccess applies to the entire directory. With the directive you can restrict it to specific files:< Files quiz.html> order deny,allow deny from all AuthType Basic AuthName "Characterology Student Authcate" AuthLDAP on AuthLDAPServer ldap://directory.characterology.com/ AuthLDAPBase "ou=Student, o=Characterology University, c=au" require valid-user satisfy any </ Files > |
19. Set Cookie using htaccess
Set Cookie with environment variableHeader set Set-Cookie "language=%{lang}e; path=/;" env=lang |
RewriteEngine On RewriteBase / RewriteRule ^(.*)(de|es|fr|it|ja|ru|en)/$ - [co=lang:$2:.yourserver.com:7200:/] |
20. Send Custom Headers
Header set P3P "policyref=\"http://www.askapache.com/w3c/p3p.xml\"" Header set X-Pingback "http://www.askapache.com/xmlrpc.php" Header set Content-Language "en-US" Header set Vary "Accept-Encoding" |
21. Blocking request based on User-Agent Header
SetEnvIfNoCase
^User-Agent$
.*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures)
HTTP_SAFE_BADBOT SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT Deny from env=HTTP_SAFE_BADBOT |
Thursday, September 26, 2013
Change style of html Tag on mouseenter and mouseleave by Jquery
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change style of html Tag on mouseenter and mouseleave by Jquery</title>
<style>
p {
color: green;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<a href="#">Move the mouse over a paragraph.</a>
<a href="#">
Like this one or the one above.</a>
<script>
$( "p" )
.on( "mouseenter", function() {
$( this ).css({
"background-color": "balck",
"font-weight": "bolder"
});
})
.on( "mouseleave", function() {
var styles = {
backgroundColor : "#fds",
fontWeight: ""
};
$( this ).css( styles );
});
</script>
</body>
</html>
Tuesday, September 24, 2013
Convert Datatable To XML in C#
public static string
ConvertDatatableToXML(DataTable dt)
{
MemoryStream str = new
MemoryStream();
dt.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new
StreamReader(str);
string xmlstr;
xmlstr =
sr.ReadToEnd();
return (xmlstr);
}
Paging With Scrolling in datalist asp.net
aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
<!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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
function test() {
// if you load with paging then remove comment below
//if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
//});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "test.aspx/GetCustomers",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("Table1").eq(0).find("TotalRows").text());
//alert(pageCount);
var customers = xml.find("Table");
customers.each(function () {
var customer = $(this);
var table = $("#dvCustomers table").eq(0).clone(true);
$(".CityName", table).html(customer.find("CityName").text());
$("#dvCustomers").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
</head>
<body style="font-family: Arial; font-size: 10pt">
<form id="form1" runat="server">
<table>
<tr>
<td>
<div id="dvCustomers">
<asp:Repeater ID="rptCustomers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td>
<b><u><span class="CityName">
<%# Eval("CityName")%></span></u></b>
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
</td>
</tr>
<tr>
<td>
<input type="button" onclick="test();" value="Load" />
</td>
</tr>
<tr>
<td valign="bottom">
<img id="loader" alt="" src="images/ajax-loader.gif" style="display: none" />
</td>
</tr>
</table>
</form>
</body>
</html>
****************************************************************
cs file
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Services;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.IO;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//int pageIndex = 1;
rptCustomers.DataSource = GetCity(1);
rptCustomers.DataBind();
}
}
public static DataSet GetCity(int pageIndex)
{
//call procedure here
DataSet ds = new DataSet();
ds = BusinessLayer.Search.Test(pageIndex, 10);
return ds;
}
[WebMethod]
public static string GetCustomers(int pageIndex)
{
System.Threading.Thread.Sleep(2000);
string dtsrt = GetCity(pageIndex).GetXml();
return dtsrt;
}
public static string ConvertDatatableToXML(DataTable dt)
{
MemoryStream str = new MemoryStream();
dt.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstr;
xmlstr = sr.ReadToEnd();
return (xmlstr);
}
}
//create procedure whitch give result in page
/*
[dbo].[Test]5,10
*/
ALTER PROC [dbo].[Test]
@PageNo INT ,
@ItemsPerPage INT
AS
BEGIN
DECLARE
@StartIdx int,
@EndIdx INT
IF @PageNo < 1 SET @PageNo = 1
IF @ItemsPerPage < 1 SET @ItemsPerPage = 10
SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1
SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1
SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY CityName) AS Row,
CityName
FROM Master.City
) AS tbl WHERE Row >= + CONVERT(VARCHAR(9), @StartIdx)
AND Row < = + CONVERT(varchar(9), @EndIdx)
--total page cout
SELECT COUNT(*)/@ItemsPerPage AS 'TotalRows' FROM Master.City
END
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
<!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 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
function test() {
// if you load with paging then remove comment below
//if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
//});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "test.aspx/GetCustomers",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("Table1").eq(0).find("TotalRows").text());
//alert(pageCount);
var customers = xml.find("Table");
customers.each(function () {
var customer = $(this);
var table = $("#dvCustomers table").eq(0).clone(true);
$(".CityName", table).html(customer.find("CityName").text());
$("#dvCustomers").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
</head>
<body style="font-family: Arial; font-size: 10pt">
<form id="form1" runat="server">
<table>
<tr>
<td>
<div id="dvCustomers">
<asp:Repeater ID="rptCustomers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td>
<b><u><span class="CityName">
<%# Eval("CityName")%></span></u></b>
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
</td>
</tr>
<tr>
<td>
<input type="button" onclick="test();" value="Load" />
</td>
</tr>
<tr>
<td valign="bottom">
<img id="loader" alt="" src="images/ajax-loader.gif" style="display: none" />
</td>
</tr>
</table>
</form>
</body>
</html>
****************************************************************
cs file
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Services;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.IO;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//int pageIndex = 1;
rptCustomers.DataSource = GetCity(1);
rptCustomers.DataBind();
}
}
public static DataSet GetCity(int pageIndex)
{
//call procedure here
DataSet ds = new DataSet();
ds = BusinessLayer.Search.Test(pageIndex, 10);
return ds;
}
[WebMethod]
public static string GetCustomers(int pageIndex)
{
System.Threading.Thread.Sleep(2000);
string dtsrt = GetCity(pageIndex).GetXml();
return dtsrt;
}
public static string ConvertDatatableToXML(DataTable dt)
{
MemoryStream str = new MemoryStream();
dt.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstr;
xmlstr = sr.ReadToEnd();
return (xmlstr);
}
}
//create procedure whitch give result in page
/*
[dbo].[Test]5,10
*/
ALTER PROC [dbo].[Test]
@PageNo INT ,
@ItemsPerPage INT
AS
BEGIN
DECLARE
@StartIdx int,
@EndIdx INT
IF @PageNo < 1 SET @PageNo = 1
IF @ItemsPerPage < 1 SET @ItemsPerPage = 10
SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1
SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1
SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY CityName) AS Row,
CityName
FROM Master.City
) AS tbl WHERE Row >= + CONVERT(VARCHAR(9), @StartIdx)
AND Row < = + CONVERT(varchar(9), @EndIdx)
--total page cout
SELECT COUNT(*)/@ItemsPerPage AS 'TotalRows' FROM Master.City
END
Sunday, September 22, 2013
Encapsulation
Encapsulation - is the ability of an object to hide its data and methods from
the rest of the world. It is one of the fundamental principles of OOPs.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
} ...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);
Subscribe to:
Posts (Atom)
Opps Part 1 : Abstraction
Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...
-
<html> <body> <table> <tr><td>Text to Save:</td></tr> <tr> <td colspan="3...
-
SQL Server has several fixed database roles such as db_datareader and db_datawriter , which grants the user read and write access res...
-
Get Yahoo Contact for C# Create new Website Create AppCode Folder Create OAuthBase.cs in AppCode Folder like us...