This blog is about the dotnet.all types of codes,news about dotnet including asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.ncluding asp.net,vb.net,c# and know about new dotnet technology.programing in asp.net,vb.net,c#, ajax, AJAX tech support for .net and discuss the new technology in dotnet.asp.net programming,dot net programming,dotnet programs,dotnet source code,source code.

Free Hosting

Free Hosting

Sunday, November 2, 2008

Adding a new list item to a drop down(asp.net code)

To add a new list item at run item to a drop down list with values

ddllist.Items.Add(New ListItem(dt.Rows(0)("ID").ToString(), dt.Rows(0)("text").ToString()))

add check box Control to the datagrid list (asp.net code)

To add check box Control to the datagrid list

//add this in the html of the datagrid



''>







To loop through the control

////////////////////////

object obj;

HtmlInputCheckBox chk;

//loop through each controls

foreach (Control objCtrl in this.DataGrid1.Items)

{

obj = objCtrl.FindControl("chkID");

chk = (HtmlInputCheckBox)(obj);

if(chk.Checked==true)

{
// do somethings
}

}

Referencing Controls in Templates after mode changes in Formview

Controls of a template are created dynamically when the template is shown, trying to get a reference to these controls in the typical way will lead to a null reference exception.

Thus, the way to get a reference to a control in a template is using the FindControl method, which looks for controls within the current naming container by its Id

Now suppose that you want to update some controls when the user switches from one FormViewMode to another. For example, you may want to get a DropDownList filled with data when entering Edit mode. At first you may think that handling the ModeChanged event of the FormView is the correct solution.

Sub EmployeeFormView_DataBound(ByVal sender As Object, ByVal e As EventArgs)
If myFormView.CurrentMode = FormViewMode.Edit Then
Dim countries As DropDownList = CType(myFormView.FindControl("countriesDropDownList"), DropDownList)
If countries IsNot Nothing Then
' fill the dropdownlist with data
End If
End If
End Sub

At this moment, all the child controls of the Edit template have already been created and the reference to the countries control is the actual DropDownList you were looking for.

Programmatically Download File from Remote Location to User Through Server

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//base.OnLoad(e);
string url = string.Empty;// Request.QueryString["DownloadUrl"];
if (url == null || url.Length == 0)
{
url = "http://img444.imageshack.us/img444/6228/initialgridsq7.jpg";
}

//Initialize the input stream
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int bufferSize = 1;

//Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg");
Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
Response.ContentType = "application/download";

//Populate the output stream
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);
Stream rs = req.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}

//Cleanup
Response.End();
ms.Close();
ms.Dispose();
rs.Dispose();
ByteBuffer = null;
}
}

ASP.NET Global Error Handler (with html report & email functionality)



Globally capture errors and exceptions in your ASP.NET site. Admin(s) can be emailed a detailed HTML report of the error, then redirect the user to a friendly error page. 100% C#, no external objects needed.

CODE :

//**************************************
// for :ASP.NET Global Error Handler (with html report & email functionality)
//**************************************
Copyright 2003 Joel Thoms
//**************************************
// Name: ASP.NET Global Error Handler (with html report & email functionality)
// Description:Globally capture errors and exceptions in your ASP.NET site. Admin(s) can be emailed a detailed HTML report of the error, then redirect the user to a friendly error page. 100% C#, no external objects needed.
// By: Joel Thoms
//
//
// Inputs:None
//
// Returns:None
//
//Assumes:None
//
//Side Effects:None
//This code is copyrighted and has limited warranties.
//Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.948/lngWId.10/qx/vb/scripts/ShowCode.htm
//for details.
//**************************************

/* Author: Joel Thoms
* Website: http://www.joel.net
* Email: (contact me through website)
* Date: 02.05.2003
*
* Copyright 2003 Joel Thoms
*
* Description:
* HtmlError generates an HTML error message from the generated Exception. HtmlError also includes
* a routine to email the error message to the admin(s).
*
* This object can be used to capture individual errors, though it's best use is to globally capture
* errors using Global.asax. Both examples are provided.
*
*
* Usage and Examples:
*
* Here is an example on how to capture a simple division by zero error.
*
* [C#]
* // Division by zero error example
* try {
* int x = 0;
* x = 1 / x;
* } catch (Exception Ex) {
* // Display Error Message to the browser
* Response.Write(HtmlError.getHtmlError(Ex));
*
* // Don't Specify SMTP Server
* HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM");
*
* // Specify SMTP Server
* //HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com");
* }
*
*
* [VB.NET]
*
* ' Division by zero error example
* Try
* Dim x As Integer = 0
* x = 1 / x
* Catch Ex As Exception
* ' Display Error Message to the browser
* Response.Write(HtmlError.getHtmlError(Ex))
*
* ' Don't Specify SMTP Server
* HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM")
*
* ' Specify SMTP Server
* 'HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com")
* End Try
*
*
* Here is an example on globally capturing errors using the Global.asax file.
*
* [C#]
*
* protected void Application_Error(Object sender, EventArgs e) {
* // Don't Specify SMTP Server
* HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM");
*
* // Specify SMTP Server
* //HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com");
*
* // Redirect User to Friendly Error Page
* Response.Redirect("/error.aspx");
* }
*
* [VB.NET]
* Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
* ' Don't Specify SMTP Server
* HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM")
*
* ' Specify SMTP Server
* 'HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com")
*
* ' Redirect User to Friendly Error Page
* Response.Redirect("/error.aspx")
* End Sub
*
*
*/
using System;
using System.Data;
using System.Web;
using System.Web.Mail;
using System.Collections.Specialized;
///

HtmlError Object.
public class HtmlError {
public HtmlError() { }
static public void sendHtmlError(Exception Ex, string email_address) { sendHtmlError(Ex, email_address, ""); }
static public void sendHtmlError(Exception Ex, string email_address, string smtp_server) {
MailMessage mail = new MailMessage();
mail.From = "server-errors@discountasp.net";
mail.To = email_address;
mail.Subject = "Uncaptured Error";
mail.Body = getHtmlError(Ex);
mail.BodyFormat = MailFormat.Html;
if (smtp_server.Length > 0) SmtpMail.SmtpServer = smtp_server;
SmtpMail.Send(mail);
}
/// Returns HTML an formatted error message.
static public string getHtmlError(Exception Ex) {
// Heading Template
const string heading = "
 
";
// Error Message Header
string html = "Error - " + Ex.Message + "

";
// Populate Error Information Collection
NameValueCollection error_info = new NameValueCollection();
error_info.Add("Message", cleanHTML(Ex.Message));
error_info.Add("Source", cleanHTML(Ex.Source));
error_info.Add("TargetSite", cleanHTML(Ex.TargetSite.ToString()));
error_info.Add("StackTrace", cleanHTML(Ex.StackTrace));
// Error Information
html += heading.Replace("", "Error Information");
html += CollectionToHtmlTable(error_info);
// QueryString Collection
html += "

" + heading.Replace("", "QueryString Collection");
html += CollectionToHtmlTable(HttpContext.Current.Request.QueryString);

// Form Collection
html += "

" + heading.Replace("", "Form Collection");
html += CollectionToHtmlTable(HttpContext.Current.Request.Form);
// Cookies Collection
html += "

" + heading.Replace("", "Cookies Collection");
html += CollectionToHtmlTable(HttpContext.Current.Request.Cookies);
// Session Variables
html += "

" + heading.Replace("", "Session Variables");
html += CollectionToHtmlTable(HttpContext.Current.Session);
// Server Variables
html += "

" + heading.Replace("", "Server Variables");
html += CollectionToHtmlTable(HttpContext.Current.Request.ServerVariables);
return html;
}
static private string CollectionToHtmlTable(NameValueCollection collection) {
// ... Template
const string TD = "";
// Table Header
string html = "\n\n"
+ " " + TD.Replace("", " Name")
+ " " + TD.Replace("", " Value") + "\n";
// No Body? -> N/A
if (collection.Count == 0) {
collection = new NameValueCollection();
collection.Add("N/A", "");
}
// Table Body
for (int i = 0; i < collection.Count; i++) {
html += ""
+ TD.Replace("", collection.Keys[i]) + "\n"
+ TD.Replace("", collection[i]) + "\n";
}
// Table Footer
return html + "
";
}
static private string CollectionToHtmlTable(HttpCookieCollection collection) {
// Overload for HttpCookieCollection collection.
// Converts HttpCookieCollection to NameValueCollection
NameValueCollection NVC = new NameValueCollection();
foreach (string item in collection) NVC.Add(item, collection[item].Value);
return CollectionToHtmlTable(NVC);
}
static private string CollectionToHtmlTable(System.Web.SessionState.HttpSessionState collection) {
// Overload for HttpSessionState collection.
// Converts HttpSessionState to NameValueCollection
NameValueCollection NVC = new NameValueCollection();
foreach (string item in collection) NVC.Add(item, collection[item].ToString());
return CollectionToHtmlTable(NVC);
}
static private string cleanHTML(string Html) {
// Cleans the string for HTML friendly display
return (Html.Length == 0) ? "" : Html.Replace("<", "<").Replace("\r\n", "
").Replace("&", "&").Replace(" ", " ");
}
}

Friday, October 31, 2008

Creating print preview page dynamically in ASP.NET(source code)





Download source files - 1 KB

Download demo project - 18.9 KB

Introduction
If you want to show a print preview page before printing any page, then you have to make a page like the one that currently is showing.

Or, if you want to print a particular section of that page, like only a DataGrid, HTML table, or any other section, and you also need to preview that in a separate page before printing, you have to create a separate print preview page to show, which is more difficult for you.

I have introduced a technique to avoid this problem. You do not need to create a separate page for print preview. You just use the JavaScript code in Script.js to create a print preview page dynamically. It will take less time to implement and so is faster. Hopefully, it will be helpful for you.

Background
I was developing a report module in my existing project. The report contents are generated dynamically by giving input (like generate by status, date range, etc). And, there is a print button to print. My client wanted to view a print preview page before printing, but we had already completed this module then. It was a really hard situation for my developers to build a print preview page for all the reports. I got this idea during that situation.

Using the code
You will just add the Script.js file in your project. The following code has been written in that file.

The getPrint(print_area) function takes the DIV ID of the section you want to print. Then, it creates a new page object and writes the necessary HTML tags, and then adds Print and Close buttons, and finally, it writes the print_area content and the closing tag.

Call the following from your ASPX page. Here, getPrint('print_area') has been added for printing the print_area DIV section. print_area is the DIV ID of the DataGrid and the other two will work for others DIVs. Whatever areas you want to print must be defined inside of DIV tags. Also include the Script.js file in the ASPX page.

Download the source code to get the getPrint() function.

I have used the following code in the demo project to generate a sample DataGrid:

Private Sub PopulateDataGrid()
'creating a sample datatable
Dim dt As New System.Data.DataTable("table1")
dt.Columns.Add("UserID")
dt.Columns.Add("UserName")
dt.Columns.Add("Phone")
Dim dr As Data.DataRow
dr = dt.NewRow
dr("UserID") = "1"
dr("UserName") = "Ferdous"
dr("Phone") = "+880 2 8125690"
dt.Rows.Add(dr)
dr = dt.NewRow
dr("UserID") = "2"
dr("UserName") = "Dorin"
dr("Phone") = "+880 2 9115690"
dt.Rows.Add(dr)
dr = dt.NewRow
dr("UserID") = "3"
dr("UserName") = "Sazzad"
dr("Phone") = "+880 2 8115690"
dt.Rows.Add(dr)
dr = dt.NewRow
dr("UserID") = "4"
dr("UserName") = "Faruk"
dr("Phone") = "+880 2 8015690"
dt.Rows.Add(dr)
DataGrid1.DataSource = dt
DataGrid1.DataBind()
End Sub


Use the following code in a separate style sheet page. See PrintStyle.css if you want to hide the Print and Close buttons during printing.

#PRINT ,#CLOSE
{
visibility:hidden;
}

Using ZIP content for delivery over HTTP (ASP.NET Source Code)

Download source code - 48.1 KB

Introduction :
Static content such as HTML and text files, styles, and client scripts can be compressed to reduce network usage. This article shows how to use already compressed content for transmission over HTTP protocol.

Background
HTTP Request and Response
An HTTP session consists of pairs of requests and responses. Every request and response has a header block that contains metadata about the content. The headers can specify the content type, the encoding, and the cache parameters of the transmitted information. We are interested in the Accept-Encoding header of an HTTP request and the Content-Encoding header of an HTTP response. Most web servers do not set the Content-Encoding header, and the HTTP communication happens as shown on Figure 1. The requested content is transmitted as is.




To save network bandwidth, a web server can be configured to compress (encode) a requested content. Most web browsers and search engine bots support the DEFLATE compression encoding [1]. You may notice Accept-Encoding is set to "gzip,deflate" that passed from your browser to a web server. We are interested in the DEFLATE encoding.

The compression comes with a price: initial response delay and more computation power is required from a web server; that decreases the number of concurrent users the web server may serve at the same time. The problem can be solved by adding a compressed content cache (see Figure 2) or by using pre-compressed data.




The second way looks more attractive – it does not require any processing power from the web server; but, it requires more work upfront such as compression of the content. That gives an additional headache for web designers and content authors when they are trying to publish their content.

ZIP File Format
The ZIP is one of the widely used compression formats. A ZIP file contains multiple files that are compressed by numerous archival methods. The most used one is DEFLATE. The file structure can be presented as two parts, the compressed data and a directory. [2] The compressed data contains pairs of local file headers and compressed data, the directory contains additional file attributes and references to local file headers.



We can use the data that was compressed by DEFLATE or no-compression methods. The DEFLATE'd data can be send over HTTP without additional re-encoding – the data is already compressed. (See Figure 4.) The Content-Encoding header has to be set to "deflate" for the HTTP response to tell a web browser that the content is encoded.



Using the Code
The solution has two parts: a utility library and a web application. The utility library contains a configuration section, web cache, path rewrite module, and ZIP reader classes. The cache classes and path rewrite module can be used only within the web application context.

The web application contains baseline implementations of the HTTP handler (httpzip.ashx) that lists and delivers contents of the registered zip folder. The handler accepts three query string parameters:

name – refers to the registered ZIP archive;
action – list or get;
file – path of the file in the ZIP archive.
To get the rfc1951.txt file from the archive that is registered as deflate-rfcs, use the following URL:

http://servername/path/httpzip.ashx?name=deflate-rfcs&action=get&file=rfc1951.txt

The ZIP files and the rewrite module can be registered in the web.config file:

For convenience, the path rewrite HTTP module is included in the utility library. It can be registered in the web.config file:


To get the rfc1951.txt file from the archive with a prefix rfcs, use the following URL:

http://servername/path/rfcs/rfc1951.txt



READ MORE


Download source code - 48.1 KB

dotnet(.Net) Project Source code Downloads and Tutorials

Email Subscrption



Enter your email address:

Delivered by FeedBurner

Feedburner Count

Unique Visitor

Design by araba-cı | MoneyGenerator Blogger Template by GosuBlogger