source code, coding, asp.net, C#, php, ruby, sql, oracle,android,node.js,javascript,linux,unix, random stuffs etc.
Saturday, September 29, 2007
Cache dataset in asp.net
===================
use the namespace : System.Web.Caching.Cache
Add dataset to cache :
Cache.Insert("yourDataSet",ds,null,DateTime.Now.AddSeconds(15),System.TimeSpan.Zero);
Remove dataset from cache:
Cache.Remove("yourDataSet");
load dataset from cache:
if(Cache["CustomersDataSet"] != null) {
ds = (DataSet)Cache["yourDataSet"];
}
else {
//logic to insert dataset to cache (i.e. load dataset and put it into cache)
}
Saturday, September 22, 2007
ASP.NET 2 life cycle listing
Application: PreAuthenticateRequest
Application: AuthenticateRequest
Application: PostAuthenticateRequest
Application: PreAuthorizeRequest
Application: AuthorizeRequest
Application: PostAuthorizeRequest
Application: PreResolveRequestCache
Application: ResolveRequestCache
Application: PostResolveRequestCache
Application: PreMapRequestHandler
Page: Construct
Application: PostMapRequestHandler
Application: PreAcquireRequestState
Application: AcquireRequestState
Application: PostAcquireRequestState
Application: PreRequestHandlerExecute
Page: AddParsedSubObject
Page: CreateControlCollection
Page: AddedControl
Page: AddParsedSubObject
Page: AddedControl
Page: ResolveAdapter
Page: DeterminePostBackMode
Page: PreInit
Control: ResolveAdapter
Control: Init
Control: TrackViewState
Page: Init
Page: TrackViewState
Page: InitComplete
Page: LoadPageStateFromPersistenceMedium
Control: LoadViewState
Page: EnsureChildControls
Page: CreateChildControls
Page: PreLoad
Page: Load
Control: DataBind
Control: Load
Page: EnsureChildControls
Page: LoadComplete
Page: EnsureChildControls
Page: PreRender
Control: EnsureChildControls
Control: PreRender
Page: PreRenderComplete
Page: SaveViewState
Control: SaveViewState
Page: SaveViewState
Control: SaveViewState
Page: SavePageStateToPersistenceMedium
Page: SaveStateComplete
Page: CreateHtmlTextWriter
Page: RenderControl
Page: Render
Page: RenderChildren
Control: RenderControl
Page: VerifyRenderingInServerForm
Page: CreateHtmlTextWriter
Control: Unload
Control: Dispose
Page: Unload
Page: Dispose
Application: PostRequestHandlerExecute
Application: PreReleaseRequestState
Application: ReleaseRequestState
Application: PostReleaseRequestState
Application: PreUpdateRequestCache
Application: UpdateRequestCache
Application: PostUpdateRequestCache
Application: EndRequest
Application: PreSendRequestHeaders
Application: PreSendRequestContent
Saturday, September 1, 2007
Reinstall IIS using command (for coders)
D:\WXPOS\Microsoft.net\Framework\v2.0.50727> aspnet_regiis -i
>iisreset
use aspnet_regiis /? for help
Monday, August 27, 2007
validate rss and atom
================
http://feedvalidator.org/
http://rss.scripting.com/
http://www.walidator.com/
http://www.ldodds.com/rss_validator/
http://feeds.archive.org/validator
http://www.ldodds.com/rss_validator/1.0/validator.html
http://aggregator.userland.com/validator
http://www.w3.org/RDF/Validator/ (RDF validator)
Web Syndication with RSS and ATOM
===========================
Syndication lets sites share information across the Web, making it easy to do things like display headlines from a site or collection of sites. Most of the syndicated feeds are written in RSS, a simple XML vocabulary (in several varieties) for summarizing information about a site. Several popular flavors of RSS are leading the pack, with upstart Atom growing in acceptance
Eg: news feeds you might find in news site, blogs etc.
There are accepted standards for syndication:
1) RSS
* RSS 0.91 (Rich Site Summary) and RSS 0.92
* RSS 1.0 (RDF Site Summary)
* RSS 2.0 (Really Simple Syndication)
2) ATOM
Formats:
For RSS 0.91
============
<rss version="0.91">
<channel>
<title>Computer Bapus Post</title>
<link>http://computerbapu.blogspot.com</link>
<description> All computer related discussions</description>
<language>en-us</language>
<image>
<url>http://computerbapu.blogspot.com/myimage.jpg</url>
<title>C# hello world</title>
<link>http://computerbapu.blogspot.com</link>
</image>
<item>
<title>C# hello world</title>
<link>http://computerbapu.blogspot.com</link>
<description>console.writeline("i am good");</description>
</item>
</channel>
</rss>
Explaination :
title
A descriptive title for this channel. This should usually be the same as the content of the HTML element title on your main site page
(maximum length : 100)
link
A URI for the channel. This should be a link to the web site that originates the feed
(maximum length is 500 characters)
description
A description of the channel, usually answering the question "What's this site all about?" Limited to 500 characters.
copyright
Copyright notice for the channel
docs
Documentation for the RSS format used by the channel
lastBuildDate
Last time channel content changed, in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST (see http://www.ietf.org/rfc/rfc822.txt)
managingEditor
Email address of managing editor for the channel
pubDate
Publication date of channel, in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST (see http://www.ietf.org/rfc/rfc822.txt)
rating
Platform for Internet Content Selection (PICS) rating (http://www.w3.org/PICS/)
skipDays
Days to skip reading channel
skipHours
Hours to skip reading channel
textInput
A text input box for the channel, such as a search box (required children include title, description, name, and link)
webMaster
Email address of webmaster for the channel
For RSS 1.0 format
=================
XML API
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns="http://purl.org/rss/1.0" xmlns:rdf="http://www.w3.org/1999/02/22
-rdf-syntax-ns#">
<channel rdf:about="http://computerbapu.blogspot.com/computerbapu.rss">
<title>Computer bapu</title>
<link>http://computerbapu.blogspot.com</link>
<description>Computer help</description>
<items>
<rdf:Seq>
<rdf:li rdf:resource="http://computerbapu.blogspot.com/myhelp.html"/>
</rdf:Seq>
</items>
</channel>
<item rdf:about="http://computerbapu.blogspot.com/myhelp.html">
<title>C# snippet for email</title>
<link>http://computerbapu.blogspot.com/email.html</link>
<description>hello world ()...</description>
</item>
</rdf:RDF>
Explaination:
rdf:RDF
The rdf:RDF element from the RDF namespace (http://www.w3.org/1999/02/22-rdf-syntax-ns#) is the document element. This element must have exactly one channel child and one or more item children (these elements are in the default namespace, http://purl.org/rss/1.0). The rdf:about attribute on channel, from the RDF namespace, identifies the feed with a URI.
title
A descriptive title for this channel.
link
A URI for the channel.
description
A description of the channel.
items
Contains the RDF elements Seq and li. The resource attribute on rdf:li contains a URI that identifies an item used later in the document
Two other possible children of channel are image and textinput, which link by means of rdf:resource attributes to other image and textinput elements, optionally used in the document as children of rdf:RDF (i.e., you can have one without the other). The image element links a graphic to the channel and must contain the trio title, link, and url; the textinput element contains a script or form that relates to the site and contains title, link, name, and description elements.
For RSS 2.0 format (quite popular now - successor of rss 0.91.)
===================================================
Example:
<rss version="2.0">
<channel>
<title>computer bapu</title>
<link>http://computerbapu.blogspot.com</link>
<pubDate>Mon, 05 Feb 2007 0:00:01 GMT</pubDate>
<description> computer help</description>
<item>
<title>RSS Help</title>
<link>http://computerbapu.blogspot.com/rsshelp.html</link>
<description>Latest News Feeds....</description>
</item>
<item>
<title>Atom Help</title>
<link>http://computerbapu.blogspot.com/atomhelp.html</link>
<description>Latest RSS News Feeds....</description>
</item>
</channel>
</rss>
Explaination:
Child element of channel:
title
Title of channel
(Required)
link
Link to channel
(Required)
description
Description of channel
(Required)
language
Language code for channel
(optional element)
image
Image that represents the channel (required children url, title, and link; optional children description, width, and height)
(optional element)
copyright
Copyright notice for the channel
(optional element)
managingEditor
Email address of managing editor
(optional element)
webMaster
Email address of webmaster
(optional element)
pubDate
Publication date of channel in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST; though not specified in RFC 822, a four-digit year is allowed (see http://www.ietf.org/rfc/rfc822.txt)
(optional element)
lastBuildDate
Last time channel content changed in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST; though not specified in RFC 822, a four-digit year is allowed (see http://www.ietf.org/rfc/rfc822.txt)
(optional element)
rating
Platform for Internet Content Selection (PICS) rating (http://www.w3.org/PICS/)
(optional element)
docs
Documentation for the RSS format used by channel
(optional element)
textInput
A text input box for the channel, such as a search box (required children include title, description, name, and link)
(optional element)
skipDays
Days to skip reading channel
(optional element)
skipHours
Hours to skip reading channel
(optional element)
category
One or more channel categories
(optional element)
generator
Name of generator program
(optional element)
cloud
Specifies a protocol for publishing and subscribing to feeds
(optional element)
ttl
Time to live in minutes
(optional element)
Child element of item:
title
Title of item
link
Link to item
description
Description of item
author
Email address of author of item (optional element)
category
One or more item categories (optional attribute domain)
(optional element)
comments
URL for comment page for item
(optional element)
enclosure
Describes an object attached to item (required attributes url, length, and type)
(optional element)
guid
Globally unique identifier
(optional element)
pubDate
Publication date in RFC 822 format
(optional element)
source
RSS channel the item came from (required attribute url)
(optional element)
Format of ATOM :
==============
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:lang="en">
<title>Computer Bapu</title>
<link rel="alternate" type="text/html"
href="http://computerbapu.blogspot.com/"/>
<author>
<name>Computer Bapu SG</name>
</author>
<tagline>This discusses about computer topics</tagline>
<modified>2007-05-14T08:56:00-01:00</modified>
<entry>
<title>C# snippet</title>
<link rel="alternate" type="text/html"
href="http://computerbapu.blogspot.com/mySnippet.html"/>
<id>http://computerbapu.blogspot.com/mySnippet.html</id>
<issued>2007-04-14T08:56:00-01:00</issued>
<modified>2007-05-14T08:56:00-01:00</modified>
</entry>
</feed>
Title: title of the document. There can be only one title.
link: Link of the resource. There can be multiple links. Type denotes media type.
Author: Author of the resource. There can be one author container within which there can be name, url, email
tagline : feeds description
show detailed error in asp.net 2.0 web.config
====================================
In web.config do the following
<customErrors mode="Off" />
This is handy for developers and testers in case when they are unable to exactly find the cause of an error. When in production this should not be used since it will show the entire detail to the laymen.
In such case use <customErrors mode="On"> to hide the detailed error.
You might want to keep show the error when run locally and hide the error when run remotely. You may achieve this using <customErrors mode="RemoteOnly">
Also if you want to redirect to a particular page when there is a error then you might use the below option:
<customErrors mode="On" defaultRedirect="ErrorTemplate.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
Quickly make a deploy folder using ASP.NET 2.0.
=======================================
run the below command a folder will be created (as specified). Also mysite is the path of your website
asp_compiler -v mysite c:\folder -f -u
Friday, August 24, 2007
Get headers using httpwebrequest and httpwebresponse
using System.Net;
private void getUrlHeaders()
{
HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://localhost/yourfile.aspx");
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
string[] names = resp.Headers.AllKeys;
foreach (string n in names) {
Response.Write(n + " : " + resp.Headers[n] + "<br>");
}
resp.Close();
}
//output
Content-Length : 2141
Cache-Control : private
Content-Type : text/html; charset=utf-8
Date : Thu, 23 Aug 2007 23:10:27 GMT
Server : Microsoft-IIS/5.1X-AspNet-Version : 2.0.50727
X-Powered-By : ASP.NET
Get the last modified date of the url using HttpWebRequest and HttpWebResponse
Get the last modified date of the url using HttpWebRequest and HttpWebResponse
private void getLastModifiedDateOfUrl(){
HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://computerbapu.blogspot.com");
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
Response.Write ("Last modified: " + resp.LastModified);
resp.Close();}
//output: Last modified: 24/08/2007 04:29:23
Use of Uri class in asp.net 2.0.
=======================
//namespaceusing System.Net;
private void showUrlParts()
{
Uri sample = new Uri("http://yourpath/bass_aei/login.aspx?param=22");
Response.Write("Host: " + sample.Host + "<br/>");
Response.Write("Port: " + sample.Port + "<br/>");
Response.Write("Scheme: " + sample.Scheme + "<br/>");
Response.Write("Local Path: " + sample.LocalPath + "<br/>");
Response.Write("Query: " + sample.Query + "<br/>");
Response.Write("Path and query: " + sample.PathAndQuery + "<br/>");
}
//Host: localhost
//Port: 80
//Scheme: http
//Local Path: /yourpath/login.aspx
//Query: ?param=22
//Path and query: /yourpath/login.aspx?param=22
Download a resource using WebClient in C#.NET
using System.net;
//download a resource from the internet.
private void downloadResource() {
WebClient wc= new WebClient();
string uri = "http://computerbapu.blogspot.com";
string fname = "myResource.txt";
try {
//this function does the work
wc.DownloadFile(uri, fname);
}
catch (WebException exc)
{
Console.WriteLine(exc);
}
catch (UriFormatException exc)
{
Console.WriteLine(exc); }
Console.WriteLine("Download is completed.");
}
Wednesday, August 22, 2007
Simple XPath query with dot net
==========================
XML Path Language (XPath) is the capability to query and locate the tree's content in a xml file.
In dot net XPath evaluation is exposed through the XPathNavigator abstract class. The navigator is an XPath processor that works on top of any XML data source that exposes the IXPathNavigable interface.The most important member of this interface is the CreateNavigator method, which returns an XPathNavigator object.
Today we will try out some xpath usin dot net
Format of users.xml
<?xml version="1.0" encoding="utf-8" ?> <users> <user> <name rollno="1">Bobby</name> <password>pass1</password> <role>Manager</role> </user> <user> <name rollno="2">Ravi</name> <password>pass2</password> <role>Data Entry Operator</role> </user></users>
/// using xpath to retrieve names
private void showXMLName() {
XPathDocument xpd = new XPathDocument("c:\\users.xml");
XPathNavigator xpn = xpd.CreateNavigator();
XPathNodeIterator xpi = xpn.Select("//users/user/name");
while (xpi.MoveNext()) {
MessageBox.Show(xpi.Current.Name + ":" + xpi.Current.Value);
}
}
// using normal xml
private void showXMLName() {
string xmlFile = "c:\\users.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlFile);
XmlNodeList nodes = doc.GetElementsByTagName("name");
foreach (XmlNode node in nodes) {
MessageBox.Show(node.ChildNodes[0].Value);
}
}
//you might want to go for attributes and other details alltogether
private void showXMLDetails() {
string xmlFile = "c:\\users.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlFile);
// Retrieve the title of every science-fiction movie.
XmlNodeList nodes = doc.SelectNodes("//users/user");
foreach (XmlNode node in nodes)
{
//MessageBox.Show(node.ChildNodes[0].Attributes.Count.ToString());
//MessageBox.Show(node.ChildNodes[0].ChildNodes[0].Value);
//MessageBox.Show(node.ChildNodes[0].LastChild.Value);
//get roll no - check the attribute at name node
MessageBox.Show(node.ChildNodes[0].Attributes["rollno"].Value );
// show name - in case of windows.net
MessageBox.Show(node.ChildNodes[0].FirstChild.Value ); //show password
MessageBox.Show(node.ChildNodes[1].FirstChild.Value); //show roles
MessageBox.Show(node.ChildNodes[2].FirstChild.Value);
}
}
//you may specify filters in xpath query.. starts-with, contains, position etc...
//get all records which starts with a particular letter
XPathNodeIterator xpi = xpn.Select("//users/user[starts-with(role,'S')]/name");
//get all records where user role is Sales
XPathNodeIterator xpi = xpn.Select("//users/user[role='Sales']/name");
//get all records which contains the string les
XPathNodeIterator xpi = xpn.Select("//users/user[contains(role,'les')]/name");
//get the record at first position.
XPathNodeIterator xpi = xpn.Select("//users/user[position()=1]/name");
//get all records where role = sales and name is bob.. you may specify and condition XPathNodeIterator xpi = xpn.Select("//users/user[role='Sales' or name='Bob']/name");
//get all records where substring for the node role is S...this demonstrate the use of substring
XPathNodeIterator xpi = xpn.Select("//users/user[substring(role,1,1)='S']/name");
Tuesday, August 21, 2007
RETRIEVE FILES FROM DIRECTORY IN C#
//string yourdirectory=Server.MapPath("yourfoldername");
string yourdirectory="C://";
string []dir=Directory.GetFiles(yourdirectory);
for (int i = 0; i < dir.Length; i++)
{
//get individual file names
string fileName = dir[i].Substring(dir[i].ToString().LastIndexOf("\\") +1);
string entirePath = dir[i].toString();
}
Thursday, June 7, 2007
Closing Database Connection In Dot NET 2.0.
Closing Database Connection In Dot NET 2.0.
===========================================
Its recommended to close connection after you utilize the resource. This was not done before (especially during the age of VB and other old application). Previously opening and closing the connection was more resource consuming hence during application startup connection was opened (As in visual basic sub main function) and it was only closed during application closure. Hence whenever application starts connection remains open even if use isn't doing anything. The major problem in keeping the connection open is...since database allows limited no of connections hence keeping the connection open without performing any database operations/actions would just waste resource. In addition when the no of connections reaches the limit it won't allow other connection to open....
Eg: This is just like storing gold ornaments without wearing it.
Hence computer scientist have come up with a new idea which is called connection pooling. Connection pooling is just like a shared connection, where database connections are created and held in a pool. A pool is created when certain connections remain open for utilization by various sessions. Whenever any application requires a connection, the provider extracts the next available connection from the pool. (Whenever a open method is called directly available connection is taken from the pool. Hence there is no resource over head at all)
Also as soon as the application closes the connection, it is returned to the pool and made available for the next application that requires connectivity. Hence opening and closing connection is just like taking charge of the resource that's it!!..hence its recommended to open the connection whenever you need it and close it as soon as you don't require it..This facilitates optimal utilization of connection resource.
Eg: This is just like sharing your gold ornaments with other relatives.
Sample connection string in dot net:
connectionString="Data Source=localhost;Initial Catalog=MyDatabase;Integrated Securing=SSPI;Min Pool Size=10";
Some of the connection string settings include:
Max Pool Size : Max No of connection allowed in the pool (default is 100)
Min Pool Size : Min No of connection retained in the pool (default is 0). The no of connections will be created when the first connection is opened, leading to a minor delay for the first request.
Pooling: When true(default), the connection is drawn from the approiate pool or if necessary is created and added to the appropriate pool
Connection Lifetime: Specifies a time interval in seconds. If a connection is returned to the pool and its creation time is older than the specified lifetime, it will be destroyed. The default is 0.(disable). This feature is useful when you want to recycle a large no of connections at once.
Also programatically you can clear pool by using methods like:
ClearPool()
ClearAllPools()
The above may be necessary when pool is full with unnecessary connections.