Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, April 30, 2010

Dynamically Generate Meta Tags for ASP.NET Pages

create an XML file that contains the data for the meta tags. Right click the website and choose Add > New Item > XML File. Name the file TagData.xml and add the following XML:

<tags pageName="/WebForm1.aspx">
<tag name="keyword" value="This is a keyword"></tag>
<tag name="description" value="This is a description"></tag>
<tag name="author" value="malcolm sheridan"></tag>
</tags>
<tags pageName="/ChildFolder/WebForm1.aspx">
<tag name="keyword" value="This is a keyword for the child pages"></tag>
<tag name="description" value="This is a description for the child pages"></tag>
<tag name="author" value="malcolm sheridan for this page too"></tag>
</tags>


In the XML above I have created a parent node called metaTags. Inside I have created a tags node which contains a pageName attribute. That value is how we will match the current requested page to the XML data. Each tags node contains a tag node that corresponds to the meta data we want sent to the browser. In this example I want to set meta tags for the all the pages to have keyword, description and author meta tags, but the values rendered to the browser will differ depending on what page the user is on. In a real world scenario this information would be stored inside a database, but I decided to keep this data inside an XML file to keep it simple and focus on how to do this.

Having outlined what meta tags we want sent to the browser, we now have to write the code that will read the XML file and dynamically add the meta tags at runtime. Seeing as though we’re using Master Pages this is the ideal spot to add it. Add the following code to read the XML file:

C#

XDocument doc = XDocument.Load(Server.MapPath("~/TagData.xml"));
var metaTags = doc.Descendants("tag")
.Where(o => o.Parent.Attribute("pageName").Value == Request.Url.AbsolutePath)
.Select(o => new
{
Value = o.Attribute("value").Value,
Name = o.Attribute("name").Value
});

VB.NET

Dim doc As XDocument = XDocument.Load(Server.MapPath("~/TagData.xml"))
Dim metaTags = doc.Descendants("tag").Where(Function(o) o.Parent.Attribute("pageName").Value = Request.Url.AbsolutePath).Select(Function(o) New With {Key .Value = o.Attribute("value").Value, Key .Name = o.Attribute("name").Value})

For flexibility and ease of use I have decided to use the power of LINQ to XML to read the XML data. To start with the XML document is load into an XDocument object. From there I have created a LINQ query to return all the tag nodes where the parent node has an attribute called pageName and the value is equal to the current page. Then the object returned is an anonymous type that has a Value and Name property. The values of those properties are the value and name attribute values.

Now that we have the data in memory, the next step is to create the meta tag and add it to the page dynamically. To do this you use the HtmlMeta class. This allows you programmatic access to the HTML meta tags. Add the following code below to your project:

C#

foreach (var item in metaTags)
{
HtmlMeta meta = new HtmlMeta();
meta.Name = item.Name;
meta.Content = item.Value;
Page.Header.Controls.Add(meta);
}

VB.NET

For Each item In metaTags
Dim meta As New HtmlMeta()
meta.Name = item.Name
meta.Content = item.Value
Page.Header.Controls.Add(meta)
Next item

The foreach loop enumerates through each item returned from the LINQ query. It assigns the Name and Content value to the HtmlMeta object. Finally the object is added to the page by calling Page.Header.Controls.Add(meta). Run the project and once the default page has loaded

Change Image Opacity on MouseOver using jQuery

This short article demonstrates how to change the opacity of an image when the user hovers the mouse over an image. This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an article.

Note that for demonstration purposes, I have included jQuery and CSS code in the same page. Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can change the opacity of an image.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Change Image Opacity on Hovertitle>
<style type="text/css">
.imgOpa
{
height:250px;
width:250px;
opacity:0.3;
filter:alpha(opacity=30);
}
<style>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('.imgOpa').each(function() {
$(this).hover(
function() {
$(this).stop().animate({ opacity: 1.0 }, 800);
},
function() {
$(this).stop().animate({ opacity: 0.3 }, 800);
})
});
});
<script>
<head>
<body>
<form id="form1" runat="server">
<div>
<h2>Hover over an Image to change its Transparency level<h2>
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl="../images/1.jpg" class="imgOpa" />
<asp:Image ID="Image2" runat="server"
ImageUrl="../images/2.jpg" class="imgOpa" />
<asp:Image ID="Image3" runat="server"
ImageUrl="../images/3.jpg" class="imgOpa" />
<asp:Image ID="Image4" runat="server"
ImageUrl="../images/4.jpg" class="imgOpa" />
<div>
<form>
<body>
<html>

In this example, observe that the images have a class attribute ‘imgOpa’. The definition of the CSS class is as shown here:
.imgOpa
{
height:250px;
width:250px;
opacity:0.3;
filter:alpha(opacity=30);
}
When the images are loaded, they are in a semitransparent state. In Firefox, Chrome and Safari, we use the opacity:n property for transparency. The opacity value can be from 0.0 - 1.0, where a lower value makes the element more transparent.
In IE 7 and later, we use filter:alpha(opacity=n) property for transparency, where the opacity value can be from 0-100.
When the user hovers the mouse over a semitransparent image, we use the jQuery hover() method to animate the opacity property from 0.3 to 1.0, thereby creating a cool effect on the images. The code to achieve this effect is shown below:
$(this).hover(
function() {
$(this).stop().animate({ opacity: 1.0 }, 800);
},
function() {
$(this).stop().animate({ opacity: 0.3 }, 800);
})
});

Displaying Time Spent on Page

In order to display the time spent on the page, we will have to create an UpdatePanel that updates every second. In order for this to not affect the rest of the page, we will put other functionality in another Update Panel. To programmatically update the time, we will use an AJAX Timer control. But first, let us begin by adding a ScriptManager control to our ASPX page:


<asp:scriptmanager id="SM1" runat="server"></asp:scriptmanager>
The next thing to do is add our UpdatePanel that will display the time spent on the page:

<asp:UpdatePanel ID="UP_Timer" runat="server" RenderMode="Inline" UpdateMode="Always">
<Triggers>
</Triggers>
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
Notice that we have included the triggers tag, as well as the content template. The trigger we are going to use will be an AJAX Timer control. Let's add that in now, as well as set the Trigger attributes:

<asp:UpdatePanel ID="UP_Timer" runat="server" RenderMode="Inline" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick" />

<asp:Literal ID="lit_Timer" runat="server" /><br />
<asp:HiddenField ID="hid_Ticker" runat="server" Value="0" />
</ContentTemplate>
</asp:UpdatePanel>
We add an AsyncPostBackTrigger and set the control ID and Event Name to match our Timer control. We also set the Interval of the Timer's tick event to 1000 milliseconds. We have added a Literal control to display the time spent on the page, and then a HiddenField to store that value. We add code to the code-behind that will run every second, on the Tick event of the Timer control (we can do this by simply adding the code manually, or double-clicking the timer control in Design view):

protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
}

protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = "Time spent on this page: " + hid_Ticker.Value.ToString();
}

First, on page load we are assigning a new value to the hidden field, of type TimeSpan. This TimeSpan is 0 hours, 0 minutes, and 0 seconds. Then on each Tick event, we add one second to that value, then display it in the Literal control. If we now run this page, we will see the page programmatically and seamlessly count up the time spent on the page.
To demonstrate that this will not interfere with other functions on the page, let's go ahead and add another Update Panel:
<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP_Timer" runat="server" RenderMode="Inline" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />

</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick" />
<asp:Literal ID="lit_Timer" runat="server" /><br />
<asp:HiddenField ID="hid_Ticker" runat="server" Value="0" />
</ContentTemplate>

</asp:UpdatePanel>

<br />

<asp:UpdatePanel ID="UP_Name" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
Add your name: <asp:TextBox ID="fld_Name" runat="server" /><br />

<br />
<asp:Button ID="btn_Submit" runat="server" Text="Submit" onclick="btn_Submit_Click" /><br />
<asp:Literal ID="lit_Name" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
}

protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = "Time spent on this page: " + hid_Ticker.Value.ToString();
}

protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = "Thanks. Your name is: " + fld_Name.Text;
}
}

Wednesday, January 6, 2010

Retrieve Images from fatabase

This is a sample code to retrieve images from data base in a gridview as to upload images to database.

use fileupload control to upload images and on upload button click retrieve image from fileupload control(named as fulimage)by writing

StreamimgStream = fuImage.PostedFile.InputStream;

and insert it into database along with other parameters.

to retrieve image from database in a gridview use generic handler. place a template in gridview and place itemtemplate in it.now add a image here like this.



and in the ImageHandler.ashx get image id from query string and retrive image from database in a datareader then return that image by this code

context.Response.BinaryWrite((Byte[])dr[0]);

here dr[0] means that image is in first field of the database.

Download the complete code here

Wednesday, October 28, 2009

Resize Image in asp.net in C#

This is a code in C# to resize an image. it takes two inputs as target image size and the image in byte format and it'll will return target sized image.

Some terms used in the code:-
Format24bppRgb - It specifies that formate is 24 bit per pixel and for each colour that is red, green and blue 8 bits are used



using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

public class ImageClass
{

private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);//User defined function to calculate image dimensions
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;//set rendering quality of canvas
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;//set interpolation mode to HighQualityBiubic
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));//drow image in canvas with new size and with specific starting location
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);//define image formate in which it is to be shown
return m.GetBuffer();//return image as byte array
}
}
}
}

private static Size CalculateDimensions(Size oldSize, int targetSize)
{
Size newSize = new Size();

//change the size according to the widh and height
if (oldSize.Height > oldSize.Width)
{
newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
newSize.Height = targetSize;
}
else
{
newSize.Width = targetSize;
newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
}
return newSize;
}
}

Friday, August 28, 2009

Refreshing a asp.net web form automaticaly

This means: forcing a page postback or redirect from a client browser without explicit user input.

Why would you want to do that? The main reasons are:

Auto-redirecting to a new URL after a brief time period
Refreshing page information periodically
Maintaining a valid session state indefinitely
Forcing a specific process to run on the server when the client session has expired.
The following methods are the constructs we have used in our web development projects:

HTML header refresh tag

The most common and best known way - a tag of the following format is placed in the HTML section of the page:

<meta http-equiv="refresh" content="8;url=http://dotnet.org.za/">

where '8' refers to the number of seconds that will elapse before the page is refreshed;
'url' is the new url redirect to. It can be excluded which means the current page will be reloaded.
This construct is useful if you have one or two pages which have to auto-refresh, and works for any HTML content type forms. The downside is the refresh interval cannot be set dynamically, and if you are testing for session timeouts on your site, you'll have to embed this construct in every page of the site.

Response.AppendHeader method
ASP.NET provides the AppendHeader method to the Response object. Typically the page refresh can be set as follows in an ASP.NET webform (in C#):


this.Response.AppendHeader("Refresh",
Convert.ToString(Session.Timeout * 60 + 5));

Here the page refresh is set to 5 seconds after the client session timeout setting specified in the web.config file.

This construct is useful as it can be placed in a base webform OnLoad() or Page_Load() response method. All derived webforms will then have the same page refresh setting when they are loaded. Obviously, if the timeout value is changed in the web.config file, no modification is required in this code and everything still works fine.

Page OnLoad method script
The same thing can be done by setting a script for the client-side HTML using the HtmlGenericControl.Attributes collection:


string onload = "window.setTimeout(
'window.location.href=window.location.href'," +
Convert.ToString( (Session.Timeout * 60 + 5) * 1000) + ");";
this.body.Attributes.Add("onload", onload);

Unfortunately, to get this to work you need to add the following attribute to the tag in the HTML:

runat="server"

and the following member in the webform code-behind class:

protected System.Web.UI.HtmlControls.HtmlGenericControl body;

Hmmm - so why do this, if it means that we have to fiddle with the HTML?

In our experience, certain ASP.NET controls in the webform actually kills the working of the previous two constructs - but this method always seems to work....regardless...in Internet Explorer...

Tuesday, August 25, 2009

Encryption and Decryption without .net APIs

This code is for encrypting and then decrypting any string. here we use teo strings NORMAL and ENCRYPT. in this method we pick characters from input and and get its index from NORMAL string and character at the same index in ENCRYPT string is replaces by original character. reverse process is used for decryption.

string NORMAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string ENCRYPT = "YO17KPLVSU50C8WE64GAI3MB2DFNZQ9JXTRH";
string strInput = "NikhilGaur";
string strEncrypted = string.Empty;
string strDecrypted = string.Empty;
string strNewChar;
string strLtr;
int iIdx;
protected EncryptionDecryptionDemo()
{
Response.Write("Original String : " + strInput);
Response.Write("
");
for (int i = 0; i < strInput.Length; i++)
{
strLtr = strInput.Substring(i, 1).ToUpper();
iIdx = NORMAL.IndexOf(strLtr);
strNewChar = ENCRYPT.Substring(iIdx, 1).ToUpper();
strEncrypted += strNewChar;
}
Response.Write("Encrypted string : " + strEncrypted);
Response.Write("
");

for (int i = 0; i < strInput.Length; i++)
{
strLtr = strEncrypted.Substring(i, 1).ToUpper();
iIdx = ENCRYPT.IndexOf(strLtr);
strNewChar = NORMAL.Substring(iIdx, 1).ToUpper();
strDecrypted += strNewChar;
}
Response.Write("Decrypted string(Original again :" + strDecrypted);
}

If you want to use any special characters you can add in variable "NORMAL" and equivalent encrypted value in variable "ENCRYPT".
"ENCRYPT" variable has the reordered letters of "NORMAL" variable.

Saturday, August 15, 2009

Move GridView Rows with up and down keys

To add client-side script event to the row to handle the event onKeyDown (we can use onKeyUp or Press also if we would like) we hook up to the GridView’s RowDataBoundEvent to make access to the current row that will be data bound. We can use the GridViewRowEventArgs’s Row property to get access to the current row. By using the Attri butes collection of t he Row property we can easy add attributes to our GridView (In this case the <tr> element that the GridView will render for us). We need to add three attributes to the row, id (to unique identify the row on the client-side), onKeyDown (to see if we press t he down or up button, for moving the marker) and the onClick (to make sure we can select a row and start moving from the selected row). The following code will add the “id” attribute to the <tr> element and it will only have the value of a counter (only to make this example simple), it will also add the onKeyDown event and call the method SelectRow when a key is pressed, and to the last the onClick event to make sure to select a start row:



private int _i = 0;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal))
{
e.Row.Attributes.Add("id", _i.ToString());
e.Row.Attributes.Add("onKeyDown", "SelectRow();");
e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString() + ");");

_i++;
}
}


The code above will make sure the GridView will render something similar to (at runtime):




<table cellspacing="0" rules="all" border="1" id="GridView1" style="border-collapse:collapse;">
<tr>
<th scope="col">CategoryID</th><th scope="col">Name</th>
</tr>
<tr id="0" onKeyDown="SelectRow();" onClick="MarkRow(0);">
<td>1</td><td>.Net 1.1</td>
</tr>
<tr id="1" onKeyDown="SelectRow();" onClick="MarkRow(1);">
<td>2</td><td>.Net Framework 2.0</td>
</tr><tr id="2" onKeyDown="SelectRow();" onClick="MarkRow(2);">
<td>3</td><td>ADO.Net 2.0</td>
</tr>
</table>
As you can see in the code above, the attribute id, onKeyDown and onClick is added to the <tr> element. The onClick event will call the MarkRow method and pass the current row as an argument to make sure the row we click on will be marked and used as a start row.

Now when we have done this, we need to add the client-side code that should handle the movement of the marker etc. We can start with the MarkRow method that will be used to mark a row (change its background color):



var currentRowId = 0;

function MarkRow(rowId)
{
if (document.getElementById(rowId) == null)
return;

if (document.getElementById(currentRowId) != null )
document.getElementById(currentRowId).style.backgroundColor = '#ffffff';

currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
}

The MarkRow will make sure a row will be marked and that a previous marked row will be remarked. The MarkRow takes one argument, rowId, which have the value of the row id to mark. The MarkRow will not do anything if the element with the specified rowId can’t be found (this will happen if we try to move out from the GridView when moving the marker with the up or down key). The curretnRowId which is a global variable will be set to the current marked row, to keep track on which row that is selected. To remark a previous selected row we use the doecument.getElementById method to get the <tr> element with the currentRowId and see if it’s not null. If it’s not null a row is already selected and we need to clear its background color (The background color of the row is used to show what row is marked). After we have cleared a selected row, we set the currentRowId to the rowId that is passed as an argument to the MarkRow method. After this is done we set the background color of the selected row to a background color used to display that the row is marked.

The MarkRow will be called when the onClick event is fired and it will make sure to set the currentRowId to the row that we have clicked on to be the start row (from where we can move the marker with the up and down key). It will also be called when we press the key up or down button to mark a new row. The method that handles the up and down keys is the SelectRow:



function SelectRow()
{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}


The SeletRow method will check if the down key is pressed (keyCode = 40) or if the up key is pressed (keyCode = 38). Note: I’m so bad of naming methods so have that in mind, but I use the name SelectRow because when a key is pressed a row should be selected ;)

When the down key is pressed, the MarkRow method will be called with the currentRowId as an argument. The currentRowId has the value of the id (which is the value of the “counter” that can also represents the index of a row) and add 1 to the id, so if we start or movement from row with id 1, we will move to row with the id 2. If we press the up key, we will decrease 1 from the current row, so if we start to move up from row with id 2, we will move to row with the id 1.
Here is the whole code:

Default.aspx.cs :



public partial class _Default : System.Web.UI.Page
{
private int _i = 0;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal))
{
e.Row.Attributes.Add("id", _i.ToString());
e.Row.Attributes.Add("onKeyDown", "SelectRow();");
e.Row.Attributes.Add("onClick", "MarkRow(" + _i.ToString() + ");");

_i++;
}
}
}

Default.aspx :



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>

<!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>Untitled Page</title>
<script type="text/javascript">

var currentRowId = 0;

function SelectRow()
{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}

function MarkRow(rowId)
{
if (document.getElementById(rowId) == null)
return;

if (document.getElementById(currentRowId) != null )
document.getElementById(currentRowId).style.backgroundColor = '#ffffff';

currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
}

</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False"
ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyBlogConnectionString %>"
SelectCommand="SELECT [CategoryID], [Name] FROM [Categories]"></asp:SqlDataSource>

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

Read a file's content from a remote webserver using the HttpWebRequest class

The HttpWebRequest class allows you to programatically make web requests against an HTTP server.

This code shows how to read a file's content from a remote webserver using the HttpWebRequest class.

Visual basic :

If Not (IsPostBack) Then
Try
Dim fr As System.Net.HttpWebRequest
Dim targetURI As New Uri("http://weblogs.asp.net/farazshahkhan")

fr = DirectCast(System.Net.HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
'In the above code http://weblogs.asp.net/farazshahkhan is used as an example
'it can be a different domain with a different filename and extension
If (fr.GetResponse().ContentLength > 0) Then
Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
Response.Write(str.ReadToEnd())
str.Close();
End If

Catch ex As System.Net.WebException
Response.Write("File does not exist.")
End Try
End If


C# :

if (!(IsPostBack))
{
try
{
System.Net.HttpWebRequest fr;
Uri targetUri = new Uri("http://weblogs.asp.net/farazshahkhan");
fr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(targetUri);
//In the above code http://weblogs.asp.net/farazshahkhan is used as an example
//it can be a different domain with a different filename and extension
if ((fr.GetResponse().ContentLength > 0))
{
System.IO.StreamReader str = new System.IO.StreamReader(fr.GetResponse().GetResponseStream());
Response.Write(str.ReadToEnd());
if (str != null) str.Close();
}
}
catch (System.Net.WebException ex)
{
Response.Write("File does not exist.");
}
}


How to export GridView to Word in asp.ner C#

In tutorial, we need "AddHeader" and "ContentType" to do the work.The AddHeader method adds a new HTML header and value to the response sent to the client. It does not replace an existing header of the same name. After a header has been added, it cannot be removed. The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.

This tutorial will show you how to export GridView to Word using ASP.NET 2.0 and C#.

First,you need to import the namespace from System.Data.SqlClient.

using System.Data.SqlClient;
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

The System.Data.SqlClient namespace contains The System.Data.SqlClient namespace is the .NET Framework Data Provider for SQL Server.The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space. In tutorial, we need "AddHeader" and "ContentType" to do the work.The AddHeader method adds a new HTML header and value to the response sent to the client. It does not replace an existing header of the same name. After a header has been added, it cannot be removed. The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.

We use the Button1_Click event to do the work. We then call "Response.AddHeader" to export a file which is named FileName.doc. We then use "Response.ContentType" to denotes the type of the file being exported.

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;

Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");

Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/vnd.word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{

}
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

The front end GridViewExportWordVB.aspx page looks something like this:


<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export to Word" Width="99px" />
<asp:GridView ID="GridView1" runat="server"> </asp:GridView>


Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!

The flow for the code behind page is as follows.

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.Text;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
string ConnectionString = "Data Source=(local);Initial Catalog=pubs;User Id=sa;Password=sa123";
SqlConnection cn1;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection cn = new SqlConnection(ConnectionString);
cn.Open();
cn1 = new SqlConnection(ConnectionString);
cn1.Open();
SqlCommand cmd = new SqlCommand("select * from [authors]", cn);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
cmd.Dispose();
cn.Dispose();
cn1.Dispose();
cn = cn1 = null;
}
}

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;

Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");

Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/vnd.word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{

}
}

Monday, August 10, 2009

Embedding the image using image URL

Here We have to discuss about , how to embed the image to an email actually , Embedding an image will affect performance so here , i am passing the image URL directly to the body tag

so , here the code..


try

{

MailMessage mail = new MailMessage();

mail.To.Add("user@gmail.com");

mail.From = new MailAddress("admin@support.com");

mail.Subject = "Test with Image";

string Body = "<b>Welcome to Pass Image URL to Email Body!</b><br><BR>Online resource for .net articles.<BR><img alt=\"\" hspace=0 src='http://www.idealsd.co.uk/images/addmenu.jpg' align=baseline border=0 >";


AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

mail.AlternateViews.Add(htmlView);

SmtpClient smtp = new SmtpClient();

smtp.Host = "smtp.gmail.com";

//specify your smtp server name/ip here
smtp.EnableSsl = true;

//enable this if your smtp server needs SSL to communicate
smtp.Credentials = new NetworkCredential("Username", "password");

// smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

smtp.Send(mail);

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

Embedding the image with an Email

We have to discuss about how to Embed an image to Email Previous Article we are discussed passing image URL directly to body tag of Email.

So , now we Embed a Image directly to Email

See the example...


try

{

MailMessage mail = new MailMessage();

mail.To.Add("user@gmail.com");

mail.From = new MailAddress("admin@support.com");

mail.Subject = "Test with Image";

string Body = "<b> Welcome to Embed image!</b><br><BR>Online resource for .net articles.<BR><img alt=\"\" hspace=0 src=\"cid:imageId\" align=baseline border=0 >";


AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

LinkedResource imagelink = new LinkedResource(Server.MapPath(".") + @"\images\sample.jpg", "image/jpg");


imagelink.ContentId = "imageId";

imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

htmlView.LinkedResources.Add(imagelink);

mail.AlternateViews.Add(htmlView);

SmtpClient smtp = new SmtpClient();

smtp.Host = "smtp.gmail.com";

//specify your smtp server name/ip here
smtp.EnableSsl = true;

//enable this if your smtp server needs SSL to communicate
smtp.Credentials = new NetworkCredential("username", "password");

// smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

smtp.Send(mail);

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

DeCompress the file using asp.net

In previous post we seen how to compress the file this will helpful when the file is large you can
compress the file.

Now we will see how to Decompress the file

Button_Click event.


DecompressFile(Server.MapPath("~/Decompressed/FindEmai_onTextfile.zip"),Server.MapPath("~/Decompressed/FindEmai_onTextfile.txt"));

Here i just swap the filename so it may confuse so use some different path(Folder) or filename

Decompress Method

public static void DecompressFile(string sourceFileName, string destinationFileName)
{

FileStream outStream;

FileStream inStream;

//Check if the source file exist.

if (File.Exists(sourceFileName))
{

//Read teh input file

inStream = File.OpenRead(sourceFileName);

//Check if the destination file exist else create once

outStream = File.Open(destinationFileName, FileMode.OpenOrCreate);

//Now create a byte array to hold the contents of the file

//Now increase the filecontent size more since the compressed file

//size will always be less then the actuak file.

byte[] fileContents = new byte[(inStream.Length * 100)];

//Read the file and decompress

GZipStream zipStream = new GZipStream(inStream, CompressionMode.Decompress, false);

//Read the contents to this byte array

int totalBytesRead = zipStream.Read(fileContents, 0, fileContents.Length);

outStream.Write(fileContents, 0, totalBytesRead);

//Now close all the streams.

zipStream.Close();

inStream.Close();

outStream.Close();

}

}

Thursday, July 23, 2009

Download files in c#

This code shows how to download files of any type from applciation

private void DownloadFile( string fname)
{
try
{
string path = MapPath( fname );
string name = System.IO.Path.GetFileName( path );
string ext = System.IO.Path.GetExtension( path );
string type = "";
// set known types based on file extension
if ( ext != null )
{
switch( ext.ToLower() )
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
case ".xml":
type = "Application/xml";
break;
case ".zip":
type = "application/zip";
break;
}
}
Response.AppendHeader( "content-disposition","attachment; filename=" + name );
if ( type != "" )
Response.ContentType = type;
Response.WriteFile( path );
}
catch(Exception ex)
{
new PowerXEditor.BL.CommonUtility().RegisterError(ex);
}
Response.End();
}

Write Error message to file ( C#)

This code shows how to write error message to file in C#.net

//Create class for write msg to file
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.IO;
///
/// Summary description for clsErrorDisplay
///
public class clsErrorDisplay
{
public void WriteToFile(string ErrStr,string Page)
{
string FilePath = System.Web.HttpContext.Current.Server.MapPath("~/ZipUnzip/log/error.txt");//Add ur path here

if (File.Exists(FilePath))
{
FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
// Write to the file using StreamWriter class
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine("\n"+Page + "\n");
m_streamWriter.WriteLine(ErrStr + "\n");
m_streamWriter.WriteLine("--------------------------------- \n ");
m_streamWriter.Flush();
m_streamWriter.Dispose();
fs.Close();
}
}
}


Call WriteToFile() from your form...
object.WriteToFile(ex.ToString(), Page.ToString());

Use of basic keywords in c#

In C# base keyword is used to call the base class constructor and base class field.

First the values are received by the derived class constructor and then passed to the base class constructor.

See The Code

class A
{
int i;
A(int n, int m)
{
x = n;
y = m
Console.WriteLine("n="+x+"m="+y);
}
}
class B:A
{
int i;
B(int a, int b):base(a,b)//calling base class constructor and passing value
{
base.i = a;//passing value to base class field
i = b;
}
public void Show()
{
Console.WriteLine("Derived class i="+i);
Console.WriteLine("Base class i="+base.i);
}
}
class MainClass
{
static void Main(string args[])
{
B b=new B(5,6);//passing value to derive class constructor
b.Show();
}
}


OUTPUT

n=5m=6
Derived class i=6
Base class i=5

Record voice from micropone in C#

Do you want to record your voice from Microphone? If yes, you can use the Microsoft APIs to solve this issue. It's a very simple approach to record your voice from Mic. I provided C#.net code to solve this issue.

1. Open C#.net web applications. And added the blow namespace.

using Microsoft.VisualBasic.Devices;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;

2. Add the below API.
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

3. Create three Buttons and given the below name and text for the buttons.

1. Record
2. SaveStop
3. Read

1. Under Record Button Click paste the below Code:

// record from microphone
mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
mciSendString("record recsound", "", 0, 0);

2. Under Save / Stop button Click,


// stop and save
mciSendString("save recsound c:\\record.wav", "", 0, 0);
mciSendString("close recsound ", "", 0, 0);
Computer c = new Computer();
c.Audio.Stop();

3. Under Read Button Click

Computer computer = new Computer();
computer.Audio.Play("c:\\record.wav", AudioPlayMode.Background);


Save and Execute it.

Thursday, July 2, 2009

Code Encryption and Decryption using a Key in C#

Many time we need to encrypt the user name and password for a high level of security..

here is the code for doing so.. We just need to include the name space System.Security in our application.. IN this code. we can use the Key to encrypt and Decrypt, thus it will provide a higher level of security.. That key we can also save in the Web config file or can provide from front end..

here is the code.

#region "Encryption & Decryption"

public static string Encrypt(stringtoEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray =UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = "543z";

if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = newMD5CryptoServiceProvider();
keyArray =hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray =UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes =new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform =tdes.CreateEncryptor();
byte[] resultArray =cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
returnConvert.ToBase64String(resultArray, 0, resultArray.Length);
}

public static string Decrypt(stringcipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray =Convert.FromBase64String(cipherString);
string key = "543z";

if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = newMD5CryptoServiceProvider();
keyArray =hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray =UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes =new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform =tdes.CreateDecryptor();
byte[] resultArray =cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdes.Clear();
returnUTF8Encoding.UTF8.GetString(resultArray);
}

#endregion

Send emails via google mail server in C#

Some time we need to send mails to others from our application, and fro this we need to use some free email server like GMAIL. here is the code using that we can use the gmail mail server to send the mails. I am simply specifying the gmail SMTP server name and the Port number in the code.. take a look…


MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(”test@test.com”);
mailMessage.Subject = “Test”;
mailMessage.Body = “This is a test mail”;
mailMessage.IsBodyHtml = true;

// Create the credentials to login to the gmail account associated with my custom domain
string sendEmailsFrom = “abc@xyz.com”;
string sendEmailsFromPassword = “password”;

NetworkCredential cred = new NetworkCredential(sendEmailsFrom, sendEmailsFromPassword);
SmtpClient mailClient = new SmtpClient(”smtp.gmail.com”, 587);
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.UseDefaultCredentials = false;
mailClient.Timeout = 30000;
mailClient.Credentials = cred;
mailClient.Send(mailMessage);