Showing posts with label Asp. Show all posts
Showing posts with label Asp. Show all posts

Labels:

In this article you can understand how to create thumbnails from images at time of Upload using ASP.NET.I create a small utility class that can convert and image into thumbnails.

Imports
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D


Public Class Image_Process
Public Function CreateThumbnail(ByVal lcFilename As String, ByVal targetSize As Integer) As Bitmap
Try
Dim loBMP As Bitmap = New Bitmap(lcFilename)
Dim loFormat As ImageFormat = loBMP.RawFormat
Dim newSize As Size = CalculateDimensions(loBMP.Size, targetSize)
Dim bmpOut As Bitmap = Nothing
bmpOut = New Bitmap(newSize.Width, newSize.Height)
Dim canvas As Graphics = Graphics.FromImage(bmpOut)
canvas.SmoothingMode = SmoothingMode.AntiAlias
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality
canvas.DrawImage(loBMP, New Rectangle(New Point(0, 0), newSize))
Return bmpOut
Catch ex As Exception
Return Nothing
End Try
End Function

Private Function CalculateDimensions(ByVal oldSize As Size, ByVal targetSize As Integer) As Size
Dim newSize As Size = New Size()
If oldSize.Height > oldSize.Width Then
newSize.Width = CInt(oldSize.Width * (CType(targetSize, Single) / CType(oldSize.Height, Single)))
newSize.Height = targetSize
Else
newSize.Width = targetSize
newSize.Height = CInt(oldSize.Height * (CType(targetSize, Single) / CType(oldSize.Width, Single)))
End If
Return newSize
End Function Microsoft.VisualBasic


End Class

The class define above can be use to covert an image into a thumbnail to be display on the list of images.
There is a method CreateThumbnail which can take two parameters and send the output in the form of Bitmap that you can save on your disk.

Below i create a sample program in which i used the above code.

Try
Dim strPath As String = Server.MapPath(Request.ApplicationPath) & "/Images/Original"
Dim filename As String = Guid.NewGuid().ToString().Substring(0, 10) & "" & video_upload.PostedFile.FileName.Remove(0, video_upload.PostedFile.FileName.LastIndexOf("."))' Dim filename As String = video_upload.PostedFile.FileName.Remove(0, video_upload.PostedFile.FileName.LastIndexOf("\") + 1)If Not IsImageFile(filename) Then
ShowMessage("This format is not supported")
Exit Sub
End If
If File.Exists(strPath & "/" & filename) Then
ShowMessage("File already exist, please rename it first")
Exit Sub
End Ifvideo_upload.PostedFile.SaveAs(strPath & "/Photos/" & filename)
video_upload.PostedFile.SaveAs(strPath & "/SnapShots/" & filename)
Dim orignalfilename As String = strPath & "/Photos/" & filename
Dim thumbfilename As String = strPath & "/SnapShots/" & filename

Here i use the function create thumbnail, and pass filename originalfilename that
convert originalfilename into 125px resolution

Dim mp As Bitmap = _img_process.CreateThumbnail(orignalfilename, 125)
If mp Is Nothing Then
ShowMessage("No image generated")
Exit Sub
End If
mp.Save(thumbfilename)

This code will provide you a clear understanding how you can manipulate images at time of upload using ASP.NET

Labels:

Uploading videos, grabbing its thumbnail and converting video to the format that is runnable on the web is now a days a popular source of increasing web site traffic online. One of the main example is www.youtube.com which provides online videos sharing features.

I published my article about Media Handling on the web in real time using FFMPEG and this article helps a lot of web developers and i get a lot of emails from developers. Now in this article i will share knowledge about a component which will really help ASP.NET developers to handle videos on the web on real time. It's Media Handler Pro component introduced recently byhttp://www.mediasoftpro.com . Media Handler Pro is a very fast and powerful encoding ASP.NET encoding component which can encode video from one format to another on the fly using ASP.NET, It is designed especially for Converting videos from any format to FLV format and grab its thumbnail in real time.

I used this component and its awesome.

Main Features included in Component:

  • Convert Videos from any format to FLV Format.
  • Set Meta - Information for FLV Video that flash player need for past play back.
  • Grab Thumbnail Image from FLV Video.
  • Extract Audio from Videos - Suitable for playing audio files , ringtones etc.
  • Convert Videos from any format to MPEG Format.

Examples :

Converting Video to FLV Format (VB.NET):

'// Create object of class Media_Handler.
Dim _mediahandler As New Media_handler()
'// Set Paths for input , output videos.
'// Set Root Path for input , output videos
Dim RootPath As String = Server.MapPath(Request.ApplicationPath)
'// Set Input Video Path.
Dim InputPath As String = RootPath & "/Default"
'// Set Output Video Path.
Dim OutputPath As String = RootPath & "/FLV"
'// Get filename and make it random in order to avoid duplication.
Dim filename As String = Guid.NewGuid().ToString().Substring(0, 10) & "" & video_upload.PostedFile.FileName.Remove(0, video_upload.PostedFile.FileName.LastIndexOf("."))
'// Upload video to input path.
video_upload.PostedFile.SaveAs(InputPath & "/" & filename)
'// After uploading convert uploaded video to flv.
Dim outfile As String = _mediahandler.Convert_Media(filename, RootPath, InputPath, OutputPath, 320, 240, 360, 25, 32, 22050)
'// Where outfile is the name of generated flv file name.


For more examples and sample codes please visit : http://www.mediasoftpro.com/sample-codes.html.


This component use FFMPEG and FLVTOOL in background for Video encoding and decoding. You must put FFMPEG and FLVTOOL in root of your web application in order to work this component properly. You can download FFMPEG and FLVTOOL from their official web sites or from http://www.mediasoftpro.com .

Showing FLV Video on the Web

After successfully encoding of your Video into flv format, you can use any flash player to display this media on your web application like in www.youtube.com.

Labels:

In this example i am going to describe how to send email with attachment in ASP.NET using fileUpload Control. I am saving the uploaded file into memory stream rather then saving it on server.And for this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server. For sending Email in ASP.NET , first of allwe need to add Syatem.Net.Mail namespace in code behind of aspx page.

C# Code Behind

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.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSend_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add(txtTo.Text);
//mail.To.Add("amit_jain_online@yahoo.com");
mail.From = new MailAddress(txtFrom.Text);
mail.Subject = txtSubject.Text;
mail.Body = txtMessage.Text;
mail.IsBodyHtml = true;

//Attach file using FileUpload Control and put the file in memory stream
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("YourGmailID@gmail.com", "YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);

}
}

VB.NET Code Behind

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mail As New MailMessage()
mail.[To].Add(txtTo.Text)
'mail.To.Add("amit_jain_online@yahoo.com");
mail.From = New MailAddress(txtFrom.Text)
mail.Subject = txtSubject.Text
mail.Body = txtMessage.Text
mail.IsBodyHtml = True

'Attach file using FileUpload Control and put the file in memory stream
If FileUpload1.HasFile Then
mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
End If
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
'Or Your SMTP Server Address
smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword")
'Or your Smtp Email ID and Password
smtp.EnableSsl = True

smtp.Send(mail)
End Sub
End Class

Labels:

Once you have published a site in ASP.NET, you'd like to know who are your visitors. One way is to check your event log on the host server. Another option is to write your own code. You'd basically like to log the IP address, and DNS name for the visitor, and it would be nice to know which page they are visiting.

To log the ip address using ASP.NET, you can call:

Request.ServerVariables["HTTP_X_FORWARDED_FOR"]

Another usefull variable is

Request.ServerVariables["REMOTE_ADDR"]

A combination of the two can be done as follows:

private string IpAddress()

{

string strIpAddress;

strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (strIpAddress == null)

{

strIpAddress = Request.ServerVariables["REMOTE_ADDR"];

}

return strIpAddress;

}

Next, you'd want to log the DNS name. To do so, you can call:

Dns.GetHostByAddress(string ipAddress)

And log the HostName property returned by the call. Now to log the address of the page being requested, you can call:

Request.Url.ToString()

So to combine all these together, here is the code to build a visitors.log file:

// Track Visitors

string ipAddress = IpAddress();

string hostName = Dns.GetHostByAddress(ipAddress).HostName;

StreamWriter wrtr = new StreamWriter(Server.MapPath("visitors.log"), true);

wrtr.WriteLine(DateTime.Now.ToString() + " | " + ipAddress + " | " + hostName + " | " + Request.Url.ToString());

wrtr.Close();

The next question is what part of your ASP.NET page can you put the above code? There are two possible places, the first would be in the Application.BeginRequest event handler, the second can be in the Master page Load event. Here is how to do it in the Load event:

using System;

using System.Configuration;

using System.Net;

using System.IO;

namespace MyWebSite

{

public partial class DefaultMasterPage : System.Web.UI.MasterPage

{

protected void Page_Load(object sender, EventArgs e)

{

// Track Visitors

string ipAddress = IpAddress();

string hostName = Dns.GetHostByAddres(ipAddress).HostName;

StreamWriter wrtr = new StreamWriter(Server.MapPath("visitors.log"),true);

wrtr.WriteLine(DateTime.Now.ToString() + " | " + ipAddress + " | " + hostName + " | " + Request.Url.ToString());

wrtr.Close();

}

private string IpAddress()

{

string strIpAddress;

strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (strIpAddress == null)

{

strIpAddress = Request.ServerVariables["REMOTE_ADDR"];

}

return strIpAddress;

}

}

}

Once you start getting some visitors, the result visitors.log file would look something like this:

4/2/2007 8:47:34 PM | 74.6.67.155 | lj612164.inktomisearch.com | http://www.mycsharpcorner.com/Post.aspx?postID=22

4/2/2007 8:53:05 PM | 66.249.66.35 | crawl-66-249-66-35.googlebot.com | http://www.mycsharpcorner.com/Default.aspx?categoryID=18

4/2/2007 9:02:41 PM | 66.249.66.35 | crawl-66-249-66-35.googlebot.com | http://www.mycsharpcorner.com/Default.aspx

4/2/2007 10:06:20 PM | 69.117.147.109 | ool-4575936d.dyn.optonline.net | http://www.mycsharpcorner.com/Post.aspx?postID=15

4/2/2007 10:12:23 PM | 72.30.216.102 | lm502014.inktomisearch.com | http://www.mycsharpcorner.com/Post.aspx?postID=22

4/2/2007 11:04:24 PM | 66.249.66.35 | crawl-66-249-66-35.googlebot.com | http://www.mycsharpcorner.com/Post.aspx?postID=15

4/2/2007 11:08:22 PM | 66.249.66.35 | crawl-66-249-66-35.googlebot.com | http://www.mycsharpcorner.com/Post.aspx?postID=23

Labels:

In most of the cases specially for reporting purpose we need to merge GridView cells or columns for client preferred output. In this example i will show you how one can merge GridView cells or columns in asp.net C#. My special focus is on to merge cells when both contains same or equal data. So that the GridView looks like a traditional report. For merging GridView cells here i want to show you a generic way so that you can use only one common method for all GridViews in your project where applicable. Let i have 3 tables named Brand,Category and product. I want to merge all brand & category if consecutive rows contains same data. Look at my below sample data:
If i directly bind the above data then professionally it won't acceptable to client. Look at the difference what we want to generate:
To produce aforementioned output add a class in your project and named it clsUIUtility. Then copy and paste the below code:
01using System;
02using System.Web.UI.WebControls;
03
04public class clsUIUtility
05{
06 public clsUIUtility()
07 {
08 }
09
10 public static void GridView_Row_Merger(GridView gridView)
11 {
12 for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
13 {
14 GridViewRow currentRow = gridView.Rows[rowIndex];
15 GridViewRow previousRow = gridView.Rows[rowIndex + 1];
16
17 for (int i = 0; i <>
18 {
19 if (currentRow.Cells[i].Text == previousRow.Cells[i].Text)
20 {
21 if (previousRow.Cells[i].RowSpan <>
22 currentRow.Cells[i].RowSpan = 2;
23 else
24 currentRow.Cells[i].RowSpan = previousRow.Cells[i].RowSpan + 1;
25 previousRow.Cells[i].Visible = false;
26 }
27 }
28 }
29 }
30}
Now add a page in your project. The HTML Markup code will look like this:




01<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Merge.aspx.cs" Inherits="GridView_Merger" %>
02
04
06<head runat="server">
07 <title>How to merge GridView cell or Columntitle>
08head>
09<body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False">
13 <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
14 <RowStyle BackColor="LightGray" />
15 <AlternatingRowStyle BackColor="LightGray" />
16 <Columns>
17 <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
18 <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
19 <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
20 Columns>
21 asp:GridView>
22 div>
23 form>
24body>
25html>
In serverside write the below code:
01using System;
02
03public partial class GridView_Merger : System.Web.UI.Page
04{
05 protected void Page_Load(object sender, EventArgs e)
06 {
07 if (!IsPostBack)
08 {
09 // Here i have used my own db utility class
10 // Bind data in your own way..its out of scope of this article
11 GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], "+
12 "P.Name [Product Name] FROM "+
13 "Brand B, Category C, Product P "+
14 "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
15 GridView1.DataBind();
16 clsUIUtility.GridView_Row_Merger(GridView1);
17 }
18 }
19}
Hope now you can merge all of your GridView Cells Or Columns in Row using ASP.NET C# within your project by writing a single line. Just call the clsUIUtility.GridView_Row_Merger method and send the GridView that you want to merge for all applicable Gridviews in your project.

There is a lot of scope to modify the generic method if GridView rows contain controls like DropDwonList, CheckBoxList, RadioButtonList etc. in a template column.