In this Post we shall develop a Java Custom Tag to display running time on a Web Page. To display time we shall need to use JavaScript. I shall then package this up as a Custom Tag. We shall use Apache Tomcat as the Web Server. However, the process is completely general.
Here is the required JavaScript:
Timer.html
<script type='text/javascript'>
window.setInterval(function ()
{
var dd=document.getElementById('d1');
var d=new Date();
dd.innerHTML= d;
},1000);
</script>
<div id='d1'></div>
the window.setInterval call will call the function after every 1000 milliseconds, i,e after one second. This will then update the inner HTML of the div.
Now, to develop a Custom Tag.
To develop a Custom Tag we need to develop a class which extends SimpleTagSupport and implement the doTag method.Place this class in a package inside the WEB-INF/classes directory.
Next we need to create a TLD file and place it anywhere inside the WEB-INF directory. This TLD needs to be referred in the taglib uri expression in the JSP page.
To, start place the jsp-api.jar file on the class path
Create a Directory CustomTags inside webapps.
Create CustomTags\WEB-INF,
Create CustomTags\WEB-INF\classes,
Create CustomTags\WEB-INF\classes\tagpackage.
I have had to create a new method to give a new name to the div to avoid any clash with any existing controls. Therefore, I have concatenated the current milliseconds. That is also why I have added the sleep for 2 milliseconds because it will give a new ID to the div if more than one are placed in the same page.
The Tag Handler Class
time.java
package tagpackage;
import javax.servlet.jsp.*;
import java.io.*;
import javax.servlet.jsp.tagext.*;
public class time extends SimpleTagSupport
{
public void doTag()throws JspException,IOException
{
try
{
java.util.Date d=new java.util.Date();
Thread.sleep(2);
long millis=d.getTime();
String name="d" + millis;
JspWriter out=getJspContext().getOut();
out.print("<script type='text/javascript'>\n");
out.print("window.setInterval(function ()\n");
out.print("{\n");
out.print("var dd=document.getElementById('" + name + "');\n");
out.print("var d=new Date();\n");
out.print("dd.innerHTML= d;\n");
out.print("},1000);\n");
out.print("</script>\n");
out.print("<div id='" + name + "'></div>");
}
catch(Exception ex)
{
}
}
}
The TLD File
MyTags.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib version="2.0" >
<tlib-version>1.0</tlib-version>
<tag>
<name>TimeTag</name>
<tag-class>tagpackage.time</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
TimeTag.jsp
<%@ taglib uri="/WEB-INF/MyTags.tld" prefix="test" %>
<test:TimeTag/>
Tuesday, December 21, 2010
Sunday, December 19, 2010
E Mailing in PHP with attachments.
In this article I am demonstrating how to send an E Mail with attachments in PHP. I have developed a class called Mailer.php.It exposes a static method called SendMail that actually sends the E Mail and true/false for success or failure.
Here is the complete class.
Class.Mailer.php
<?php
class Mailer
{
public static function SendMail($mailto,$mailfrom,$mailsubject,$_FILES,$msg)
{
$hasattachment=false;
$msg=stripslashes($msg);
if(!$_FILES)//Check if a FILES collection exists
{
//If no file exists, just mail it
$mailfrom="From: $mailfrom";
if(mail($mailto,$mailsubject,$msg,$mailfrom))
return true;
else
return false;
}
else
{
//Try and attach the file
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
if (is_uploaded_file($attachment))
{
//attaching the file
$hasattachment=true;
$fp = fopen($attachment, "rb"); //Open the attachment
$data = fread($fp, filesize($attachment)); //Read the attachment
$data = chunk_split(base64_encode($data)); //Split it and encode it for sending
fclose($fp);
}
}
$headers = "From: $mailfrom\n";
$headers .= "Reply-To: $mailto\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
$headers .= "X-Sender: $mailfrom>\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . "$mailfrom" . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
$message .= "$msg\n";//Add the message
$message .= "\n";
$message .= "------=MIME_BOUNDRY_message_parts--\n";
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message\n";
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
$message .= $data; //The attachment
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message--\n";
if(mail($mailto,$mailsubject,$message,$headers))
return true;
else
return false;
}
}
?>
The HTML Page that contains the HTML Form.
Mail.html
<body bgcolor="orange">
<center>
<form enctype="multipart/form-data" id="name" name="name" action="SendMail.php" method="post">
<table width="80%" border="2">
<tr><td colspan="2" align="center"><h1>Email System through PHP</h1></td></tr>
<tr><td width="15%">Sender</td><td><input type="text" id="sender" name="sender"></td></tr>
<tr><td width="15%">Receiver</td><td><input type="text" id="receiver" name="receiver"></td></tr>
<tr><td width="15%">Subject</td><td><input type="text" id="subject" name="subject"></td></tr>
<tr><td width="15%">Message</td><td><textarea id="message" name="message" rows="7" cols="30"></textarea></td></tr>
<tr><td>Attachment</td><td><input type="file" name="attachment" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Submit"></td></tr>
</form>
</table>
</center>
The SendMail.php page
SendMail.php
<?php
require_once('Class.Mailer.php');
//if no attachments are desired use null instead of $_FILES
$result=Mailer::SendMail($_POST['receiver'],$_POST['sender'],$_POST['subject'],$_FILES,$_POST['message']);
if($result)
print("Mail Sent");
else
print("Mail Sending Failed");
?>
The received Mail
And here is the attachment.
In further posts, we will learn to do the same things in Java Server Programming & ASP.NET.
Here is the complete class.
Class.Mailer.php
<?php
class Mailer
{
public static function SendMail($mailto,$mailfrom,$mailsubject,$_FILES,$msg)
{
$hasattachment=false;
$msg=stripslashes($msg);
if(!$_FILES)//Check if a FILES collection exists
{
//If no file exists, just mail it
$mailfrom="From: $mailfrom";
if(mail($mailto,$mailsubject,$msg,$mailfrom))
return true;
else
return false;
}
else
{
//Try and attach the file
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
if (is_uploaded_file($attachment))
{
//attaching the file
$hasattachment=true;
$fp = fopen($attachment, "rb"); //Open the attachment
$data = fread($fp, filesize($attachment)); //Read the attachment
$data = chunk_split(base64_encode($data)); //Split it and encode it for sending
fclose($fp);
}
}
$headers = "From: $mailfrom\n";
$headers .= "Reply-To: $mailto\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
$headers .= "X-Sender: $mailfrom>\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . "$mailfrom" . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
$message .= "$msg\n";//Add the message
$message .= "\n";
$message .= "------=MIME_BOUNDRY_message_parts--\n";
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message\n";
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
$message .= $data; //The attachment
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message--\n";
if(mail($mailto,$mailsubject,$message,$headers))
return true;
else
return false;
}
}
?>
The HTML Page that contains the HTML Form.
Mail.html
<body bgcolor="orange">
<center>
<form enctype="multipart/form-data" id="name" name="name" action="SendMail.php" method="post">
<table width="80%" border="2">
<tr><td colspan="2" align="center"><h1>Email System through PHP</h1></td></tr>
<tr><td width="15%">Sender</td><td><input type="text" id="sender" name="sender"></td></tr>
<tr><td width="15%">Receiver</td><td><input type="text" id="receiver" name="receiver"></td></tr>
<tr><td width="15%">Subject</td><td><input type="text" id="subject" name="subject"></td></tr>
<tr><td width="15%">Message</td><td><textarea id="message" name="message" rows="7" cols="30"></textarea></td></tr>
<tr><td>Attachment</td><td><input type="file" name="attachment" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Submit"></td></tr>
</form>
</table>
</center>
The SendMail.php page
SendMail.php
<?php
require_once('Class.Mailer.php');
//if no attachments are desired use null instead of $_FILES
$result=Mailer::SendMail($_POST['receiver'],$_POST['sender'],$_POST['subject'],$_FILES,$_POST['message']);
if($result)
print("Mail Sent");
else
print("Mail Sending Failed");
?>
The received Mail
And here is the attachment.
In further posts, we will learn to do the same things in Java Server Programming & ASP.NET.
Saturday, December 18, 2010
Drawing on the Desktop using C#
In this application we shall learn how to draw over the desktop. To do this we shall make use of the following windows api functions.
[DllImport("GDI32.dll")]
private static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
private static extern int SelectObject(int hdc, int hgdiobj);
[DllImport("User32.dll")]
private static extern int GetDesktopWindow();
[DllImport("User32.dll")]
private static extern int GetWindowDC(int hWnd);
[DllImport("GDI32.dll")]
private static extern int LineTo(int hdc, int x, int y);
[DllImport("GDI32.dll")]
private static extern int MoveToEx(int hdc, int x, int y,ref Point lppoint);
[DllImport("GDI32.dll")]
private static extern int CreatePen(int penstyle, int width, int color);
Using these functions I have developed a class called DesktopDrawing
which contains a static method public static void DrawALine(int x1,int y1,int x2,int y2,int width,Color clr)
The parameters are self explanatory.
The method makes use of the following Windows API functions:-
1) GetDesktopWindow gets a handle to the Desktop.
2) GetWindowDC gets the Device Context to a window given it's handle.
3) CreatePen Creates a Pen for drawing, given a DrawMode, width and Color.
4) SelectObject Selects a Pen for drawing into a DeviceContext.
5) MoveToEx Moves the Current Point of a DeviceContext to a specified X,Y Position. It also returns the new Point by a reference Parameter.
6) LineTo Draws a Line from the Current Point in a DeviceContext to a given X,Y Position .
7) DeleteDC Deletes a DeviceContext and releases the resources used.
8) DeleteObject Deletes an Object and releases the used resources.
The Application
DesktopDrawing.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DesktopPainter
{
public static class DesktopDrawing
{
[DllImport("GDI32.dll")]
private static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
private static extern int SelectObject(int hdc, int hgdiobj);
[DllImport("User32.dll")]
private static extern int GetDesktopWindow();
[DllImport("User32.dll")]
private static extern int GetWindowDC(int hWnd);
[DllImport("GDI32.dll")]
private static extern int LineTo(int hdc, int x, int y);
[DllImport("GDI32.dll")]
private static extern int MoveToEx(int hdc, int x, int y,ref Point lppoint);
[DllImport("GDI32.dll")]
private static extern int CreatePen(int penstyle, int width, int color);
public static void DrawALine(int x1,int y1,int x2,int y2,int width,Color clr)
{
Point p=new Point ();
int hdcSrc = GetWindowDC(GetDesktopWindow());
int newcolor =System.Drawing .ColorTranslator.ToWin32 ( clr);
int newpen=CreatePen(0,width , newcolor);
SelectObject(hdcSrc,newpen );
MoveToEx(hdcSrc, x1, y1, ref p);
LineTo(hdcSrc,x2,y2);
DeleteDC(hdcSrc);
DeleteObject(newpen);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DesktopPainter
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DesktopPainter
{
public partial class Form1 : Form
{
bool IsColorDialogOpened = false;
int px = 0, py = 0;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (!chkDraw.Checked || IsColorDialogOpened )
return;
int x = Cursor.Position.X;
int y = Cursor.Position.Y;
DesktopDrawing.DrawALine(px, py, x, y,50, lblDrawingColor.BackColor );
px = x;
py = y;
}
private void lblDrawingColor_Click(object sender, EventArgs e)
{
IsColorDialogOpened = true;
cld.Color = lblDrawingColor.BackColor;
cld.AllowFullOpen = true;
cld.ShowDialog(this);
lblDrawingColor.BackColor = cld.Color;
IsColorDialogOpened = false;
}
private void chkDraw_CheckedChanged(object sender, EventArgs e)
{
px = Cursor.Position.X;
py = Cursor.Position.Y;
}
}
}
Form1.Designer.cs
namespace DesktopPainter
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.picDesktop = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.cld = new System.Windows.Forms.ColorDialog();
this.lblDrawingColor = new System.Windows.Forms.Button();
this.chkDraw = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).BeginInit();
this.SuspendLayout();
//
// picDesktop
//
this.picDesktop.Dock = System.Windows.Forms.DockStyle.Fill;
this.picDesktop.Location = new System.Drawing.Point(0, 0);
this.picDesktop.Name = "picDesktop";
this.picDesktop.Size = new System.Drawing.Size(782, 464);
this.picDesktop.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picDesktop.TabIndex = 0;
this.picDesktop.TabStop = false;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 200;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// cld
//
this.cld.Color = System.Drawing.Color.Red;
//
// lblDrawingColor
//
this.lblDrawingColor.BackColor = System.Drawing.Color.Red;
this.lblDrawingColor.Location = new System.Drawing.Point(122, 71);
this.lblDrawingColor.Name = "lblDrawingColor";
this.lblDrawingColor.Size = new System.Drawing.Size(156, 33);
this.lblDrawingColor.TabIndex = 1;
this.lblDrawingColor.Text = "&Drawing Color";
this.lblDrawingColor.UseVisualStyleBackColor = false;
this.lblDrawingColor.Click += new System.EventHandler(this.lblDrawingColor_Click);
//
// chkDraw
//
this.chkDraw.AutoSize = true;
this.chkDraw.Location = new System.Drawing.Point(357, 86);
this.chkDraw.Name = "chkDraw";
this.chkDraw.Size = new System.Drawing.Size(79, 17);
this.chkDraw.TabIndex = 2;
this.chkDraw.Text = "Draw &Lines";
this.chkDraw.UseVisualStyleBackColor = true;
this.chkDraw.CheckedChanged += new System.EventHandler(this.chkDraw_CheckedChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(782, 464);
this.Controls.Add(this.chkDraw);
this.Controls.Add(this.lblDrawingColor);
this.Controls.Add(this.picDesktop);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox picDesktop;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.ColorDialog cld;
private System.Windows.Forms.Button lblDrawingColor;
private System.Windows.Forms.CheckBox chkDraw;
}
}
I have deliberately kept it a bit rough round the edges while still providing the basic requirements. Enter your E Mail in the comments if you want a zip of the Application.
[DllImport("GDI32.dll")]
private static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
private static extern int SelectObject(int hdc, int hgdiobj);
[DllImport("User32.dll")]
private static extern int GetDesktopWindow();
[DllImport("User32.dll")]
private static extern int GetWindowDC(int hWnd);
[DllImport("GDI32.dll")]
private static extern int LineTo(int hdc, int x, int y);
[DllImport("GDI32.dll")]
private static extern int MoveToEx(int hdc, int x, int y,ref Point lppoint);
[DllImport("GDI32.dll")]
private static extern int CreatePen(int penstyle, int width, int color);
Using these functions I have developed a class called DesktopDrawing
which contains a static method public static void DrawALine(int x1,int y1,int x2,int y2,int width,Color clr)
The parameters are self explanatory.
The method makes use of the following Windows API functions:-
1) GetDesktopWindow gets a handle to the Desktop.
2) GetWindowDC gets the Device Context to a window given it's handle.
3) CreatePen Creates a Pen for drawing, given a DrawMode, width and Color.
4) SelectObject Selects a Pen for drawing into a DeviceContext.
5) MoveToEx Moves the Current Point of a DeviceContext to a specified X,Y Position. It also returns the new Point by a reference Parameter.
6) LineTo Draws a Line from the Current Point in a DeviceContext to a given X,Y Position .
7) DeleteDC Deletes a DeviceContext and releases the resources used.
8) DeleteObject Deletes an Object and releases the used resources.
The Application
DesktopDrawing.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DesktopPainter
{
public static class DesktopDrawing
{
[DllImport("GDI32.dll")]
private static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
private static extern int SelectObject(int hdc, int hgdiobj);
[DllImport("User32.dll")]
private static extern int GetDesktopWindow();
[DllImport("User32.dll")]
private static extern int GetWindowDC(int hWnd);
[DllImport("GDI32.dll")]
private static extern int LineTo(int hdc, int x, int y);
[DllImport("GDI32.dll")]
private static extern int MoveToEx(int hdc, int x, int y,ref Point lppoint);
[DllImport("GDI32.dll")]
private static extern int CreatePen(int penstyle, int width, int color);
public static void DrawALine(int x1,int y1,int x2,int y2,int width,Color clr)
{
Point p=new Point ();
int hdcSrc = GetWindowDC(GetDesktopWindow());
int newcolor =System.Drawing .ColorTranslator.ToWin32 ( clr);
int newpen=CreatePen(0,width , newcolor);
SelectObject(hdcSrc,newpen );
MoveToEx(hdcSrc, x1, y1, ref p);
LineTo(hdcSrc,x2,y2);
DeleteDC(hdcSrc);
DeleteObject(newpen);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DesktopPainter
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DesktopPainter
{
public partial class Form1 : Form
{
bool IsColorDialogOpened = false;
int px = 0, py = 0;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (!chkDraw.Checked || IsColorDialogOpened )
return;
int x = Cursor.Position.X;
int y = Cursor.Position.Y;
DesktopDrawing.DrawALine(px, py, x, y,50, lblDrawingColor.BackColor );
px = x;
py = y;
}
private void lblDrawingColor_Click(object sender, EventArgs e)
{
IsColorDialogOpened = true;
cld.Color = lblDrawingColor.BackColor;
cld.AllowFullOpen = true;
cld.ShowDialog(this);
lblDrawingColor.BackColor = cld.Color;
IsColorDialogOpened = false;
}
private void chkDraw_CheckedChanged(object sender, EventArgs e)
{
px = Cursor.Position.X;
py = Cursor.Position.Y;
}
}
}
Form1.Designer.cs
namespace DesktopPainter
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.picDesktop = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.cld = new System.Windows.Forms.ColorDialog();
this.lblDrawingColor = new System.Windows.Forms.Button();
this.chkDraw = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).BeginInit();
this.SuspendLayout();
//
// picDesktop
//
this.picDesktop.Dock = System.Windows.Forms.DockStyle.Fill;
this.picDesktop.Location = new System.Drawing.Point(0, 0);
this.picDesktop.Name = "picDesktop";
this.picDesktop.Size = new System.Drawing.Size(782, 464);
this.picDesktop.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picDesktop.TabIndex = 0;
this.picDesktop.TabStop = false;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 200;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// cld
//
this.cld.Color = System.Drawing.Color.Red;
//
// lblDrawingColor
//
this.lblDrawingColor.BackColor = System.Drawing.Color.Red;
this.lblDrawingColor.Location = new System.Drawing.Point(122, 71);
this.lblDrawingColor.Name = "lblDrawingColor";
this.lblDrawingColor.Size = new System.Drawing.Size(156, 33);
this.lblDrawingColor.TabIndex = 1;
this.lblDrawingColor.Text = "&Drawing Color";
this.lblDrawingColor.UseVisualStyleBackColor = false;
this.lblDrawingColor.Click += new System.EventHandler(this.lblDrawingColor_Click);
//
// chkDraw
//
this.chkDraw.AutoSize = true;
this.chkDraw.Location = new System.Drawing.Point(357, 86);
this.chkDraw.Name = "chkDraw";
this.chkDraw.Size = new System.Drawing.Size(79, 17);
this.chkDraw.TabIndex = 2;
this.chkDraw.Text = "Draw &Lines";
this.chkDraw.UseVisualStyleBackColor = true;
this.chkDraw.CheckedChanged += new System.EventHandler(this.chkDraw_CheckedChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(782, 464);
this.Controls.Add(this.chkDraw);
this.Controls.Add(this.lblDrawingColor);
this.Controls.Add(this.picDesktop);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox picDesktop;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.ColorDialog cld;
private System.Windows.Forms.Button lblDrawingColor;
private System.Windows.Forms.CheckBox chkDraw;
}
}
I have deliberately kept it a bit rough round the edges while still providing the basic requirements. Enter your E Mail in the comments if you want a zip of the Application.
Thursday, December 16, 2010
Capturing The Desktop using C#
In previous posts we have learnt how to use pictures in Oracle vis-a-vis Java, in MySQL via PHP, and MS SQL Server via ASP.NET, Windows Forms Applications, and WCF. In this post I will show how to capture the Desktop as an Image and display it in a Picture Box in a Windows Application. To do this we need to access the Windows API. I have developed a static class DesktopImageCapturer for this purpose. It captures the Desktop and returns it as a System.Drawing.Image object.
Here is the class
DesktopImageCapturer.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DesktopCapturer
{
public static class DesktopImageCapturer
{
[DllImport("GDI32.dll")]
private static extern bool BitBlt(int hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, int hdcSrc, int nXSrc, int nYSrc, int dwRop);
[DllImport("GDI32.dll")]
private static extern int CreateCompatibleBitmap(int hdc, int nWidth, int nHeight);
[DllImport("GDI32.dll")]
private static extern int CreateCompatibleDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
private static extern int GetDeviceCaps(int hdc, int nIndex);
[DllImport("GDI32.dll")]
private static extern int SelectObject(int hdc, int hgdiobj);
[DllImport("User32.dll")]
private static extern int GetDesktopWindow();
[DllImport("User32.dll")]
private static extern int GetWindowDC(int hWnd);
[DllImport("User32.dll")]
private static extern int ReleaseDC(int hWnd, int hDC);
public static Image GetTheDesktop()
{
int hdcSrc = GetWindowDC(GetDesktopWindow());
int hdcDest = CreateCompatibleDC(hdcSrc);
int hBitmap = CreateCompatibleBitmap(hdcSrc, GetDeviceCaps(hdcSrc, 8), GetDeviceCaps(hdcSrc, 10));
SelectObject(hdcDest, hBitmap);
BitBlt(hdcDest, 0, 0, GetDeviceCaps(hdcSrc, 8),
GetDeviceCaps(hdcSrc, 10), hdcSrc, 0, 0, 0x00CC0020);
Image img = Image.FromHbitmap(new IntPtr(hBitmap));
ReleaseDC(GetDesktopWindow(), hdcSrc);
DeleteDC(hdcDest);
DeleteObject(hBitmap);
return img;
}
}
}
Here is the Windows Form
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DesktopCapturer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
picDesktop.Image = DesktopImageCapturer.GetTheDesktop ();
}
}
}
Form1.Designer.cs
namespace DesktopCapturer
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.picDesktop = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).BeginInit();
this.SuspendLayout();
//
// picDesktop
//
this.picDesktop.Dock = System.Windows.Forms.DockStyle.Fill;
this.picDesktop.Location = new System.Drawing.Point(0, 0);
this.picDesktop.Name = "picDesktop";
this.picDesktop.Size = new System.Drawing.Size(782, 464);
this.picDesktop.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picDesktop.TabIndex = 0;
this.picDesktop.TabStop = false;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 5000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(782, 464);
this.Controls.Add(this.picDesktop);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox picDesktop;
private System.Windows.Forms.Timer timer1;
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DesktopCapturer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Here is the class
DesktopImageCapturer.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DesktopCapturer
{
public static class DesktopImageCapturer
{
[DllImport("GDI32.dll")]
private static extern bool BitBlt(int hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, int hdcSrc, int nXSrc, int nYSrc, int dwRop);
[DllImport("GDI32.dll")]
private static extern int CreateCompatibleBitmap(int hdc, int nWidth, int nHeight);
[DllImport("GDI32.dll")]
private static extern int CreateCompatibleDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
private static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
private static extern int GetDeviceCaps(int hdc, int nIndex);
[DllImport("GDI32.dll")]
private static extern int SelectObject(int hdc, int hgdiobj);
[DllImport("User32.dll")]
private static extern int GetDesktopWindow();
[DllImport("User32.dll")]
private static extern int GetWindowDC(int hWnd);
[DllImport("User32.dll")]
private static extern int ReleaseDC(int hWnd, int hDC);
public static Image GetTheDesktop()
{
int hdcSrc = GetWindowDC(GetDesktopWindow());
int hdcDest = CreateCompatibleDC(hdcSrc);
int hBitmap = CreateCompatibleBitmap(hdcSrc, GetDeviceCaps(hdcSrc, 8), GetDeviceCaps(hdcSrc, 10));
SelectObject(hdcDest, hBitmap);
BitBlt(hdcDest, 0, 0, GetDeviceCaps(hdcSrc, 8),
GetDeviceCaps(hdcSrc, 10), hdcSrc, 0, 0, 0x00CC0020);
Image img = Image.FromHbitmap(new IntPtr(hBitmap));
ReleaseDC(GetDesktopWindow(), hdcSrc);
DeleteDC(hdcDest);
DeleteObject(hBitmap);
return img;
}
}
}
Here is the Windows Form
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DesktopCapturer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
picDesktop.Image = DesktopImageCapturer.GetTheDesktop ();
}
}
}
Form1.Designer.cs
namespace DesktopCapturer
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.picDesktop = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).BeginInit();
this.SuspendLayout();
//
// picDesktop
//
this.picDesktop.Dock = System.Windows.Forms.DockStyle.Fill;
this.picDesktop.Location = new System.Drawing.Point(0, 0);
this.picDesktop.Name = "picDesktop";
this.picDesktop.Size = new System.Drawing.Size(782, 464);
this.picDesktop.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picDesktop.TabIndex = 0;
this.picDesktop.TabStop = false;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 5000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(782, 464);
this.Controls.Add(this.picDesktop);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.picDesktop)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox picDesktop;
private System.Windows.Forms.Timer timer1;
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DesktopCapturer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
In a subsequent Post I'll show how we can capture the Screen via a Java Application, and also how to send this Image through a WCF Service. Maybe some you can refer the old WCF app and do it yourself.
Labels:
C#,
Capturing the Desktop,
Champak,
Champak Roy,
Varanasi
Tuesday, December 14, 2010
Storing Pictures in Oracle 10G through Java Servlets, recovering it and displaying it through a Servlet.
This Post explains how to store a picture in an Oracle 10G database. Then It also explains how to retrieve the picture and display it in a web page.The Image is stored in a BLOB.
create table Pictures(PictureName varchar(100) primary key,Picture Blob)
Then download the org.apache.commons.fileupload, and the org.apache.commons.io packages from the Apache website. I bundled it into a jar file, called it org.jar and added it to the lib directory under Tomcat 6.0
Then develop a website and call it PicturesSite, and copy it to the webapps directory in Tomcat 6.0
Then create a resource entry in Context.xml file under the conf directory.
context.xml
<Resource name="Pictures" Auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:XE"
username="system" password="hypatia"
MaxActive="20" MaxIdle="10" MaxWait="-1"/>
Of course the ojdbc14.jar file (It contains the OracleDriver) has to be copied into Tomcat6.0\lib
Here is the code for the PictureUploaderForm. It will upload two pictures at one go.
PicUpload.html
<html>
<body>
<title>FILE UPLOADING</title>
<form id="f1" enctype="multipart/form-data" method="post" action="uploaderservlet">
PICTURE:<input type="FILE" id="picture" name="picture" />
PICTURE:<input type="FILE" id="pictureWa" name="pictureWa" />
<br/>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
uploaderservlet.java
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
public class uploaderservlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
Context initcontext=new InitialContext();
Context envcontext=(Context)initcontext.lookup("java:/comp/env");
DataSource ds=(DataSource)envcontext.lookup("Pictures");
Connection con=ds.getConnection();
response.getWriter().println(con);
PreparedStatement smt=con.prepareStatement("insert into pictures values(?,?)");
/**********************************/
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(100000000);
fu.setSizeThreshold(4096);
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
while(i.hasNext())
{
FileItem fi = (FileItem)i.next();
String filename = fi.getName();
if(filename!=null)
{
response.getWriter().println(filename);
int last=filename.lastIndexOf("\\");
filename=filename.substring(last+1).trim();
String originalfilename=filename;
filename="webapps\\PicturesSite\\images\\" +filename;
File f=new java.io.File(filename);
fi.write(f);
fi.getOutputStream().flush();
fi.getOutputStream().close();
response.getWriter().println("File uploaded successfully" );
smt.setString(1,originalfilename);
FileInputStream fs=new FileInputStream(f);
smt.setBinaryStream(2,fs,(int)f.length());
smt.executeUpdate();
fs.close();
f=null;
}
}
con.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Here is the database after the file uploading is done.
To retrieve the Picture I have used a servlet and written the data to the OutputStream of the response. In a subsequent post I'll explain how to do it via a Java Bean, and a Custom Tag.
Here is the Servlet
showpicture.java
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class showpicture extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
String name=request.getParameter("picturename");
Context initcontext=new InitialContext();
Context envcontext=(Context)initcontext.lookup("java:/comp/env");
DataSource ds=(DataSource)envcontext.lookup("Pictures");
Connection con=ds.getConnection();
PreparedStatement ps=con.prepareStatement("select picture from pictures where picturename=?");
ps.setString(1,name);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
Blob b=rs.getBlob(1);
OutputStream out=response.getOutputStream();
InputStream in=b.getBinaryStream();
int n=in.read();
while(n!=-1)
{
out.write(n);
n=in.read();
}
out.flush();
out.close();
in.close();
con.close();
}
}
catch(Exception ex)
{
}
}
}
To display the Pictures in an HTML page use the img tag, and send the PictureName via a GET name value pair.
Here is the HTML Page
Pictures.html
<img src="showpicture?picturename=Champak.jpg" alt="Champak.jpg" width="300" height="300"/>
<img src="showpicture?picturename=design.jpg" alt="design.jpg" width="300" height="300"/>
web.xml
<web-app>
<servlet>
<servlet-name>MYFILE</servlet-name>
<servlet-class>servlets.uploaderservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MYFILE</servlet-name>
<url-pattern>/uploaderservlet/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>showimages</servlet-name>
<servlet-class>servlets.showpicture</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showimages</servlet-name>
<url-pattern>/showpicture/*</url-pattern>
</servlet-mapping>
</web-app>
create table Pictures(PictureName varchar(100) primary key,Picture Blob)
Then download the org.apache.commons.fileupload, and the org.apache.commons.io packages from the Apache website. I bundled it into a jar file, called it org.jar and added it to the lib directory under Tomcat 6.0
Then develop a website and call it PicturesSite, and copy it to the webapps directory in Tomcat 6.0
Then create a resource entry in Context.xml file under the conf directory.
context.xml
<Resource name="Pictures" Auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:XE"
username="system" password="hypatia"
MaxActive="20" MaxIdle="10" MaxWait="-1"/>
Of course the ojdbc14.jar file (It contains the OracleDriver) has to be copied into Tomcat6.0\lib
Here is the code for the PictureUploaderForm. It will upload two pictures at one go.
PicUpload.html
<html>
<body>
<title>FILE UPLOADING</title>
<form id="f1" enctype="multipart/form-data" method="post" action="uploaderservlet">
PICTURE:<input type="FILE" id="picture" name="picture" />
PICTURE:<input type="FILE" id="pictureWa" name="pictureWa" />
<br/>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
uploaderservlet.java
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
public class uploaderservlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
Context initcontext=new InitialContext();
Context envcontext=(Context)initcontext.lookup("java:/comp/env");
DataSource ds=(DataSource)envcontext.lookup("Pictures");
Connection con=ds.getConnection();
response.getWriter().println(con);
PreparedStatement smt=con.prepareStatement("insert into pictures values(?,?)");
/**********************************/
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(100000000);
fu.setSizeThreshold(4096);
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
while(i.hasNext())
{
FileItem fi = (FileItem)i.next();
String filename = fi.getName();
if(filename!=null)
{
response.getWriter().println(filename);
int last=filename.lastIndexOf("\\");
filename=filename.substring(last+1).trim();
String originalfilename=filename;
filename="webapps\\PicturesSite\\images\\" +filename;
File f=new java.io.File(filename);
fi.write(f);
fi.getOutputStream().flush();
fi.getOutputStream().close();
response.getWriter().println("File uploaded successfully" );
smt.setString(1,originalfilename);
FileInputStream fs=new FileInputStream(f);
smt.setBinaryStream(2,fs,(int)f.length());
smt.executeUpdate();
fs.close();
f=null;
}
}
con.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Here is the database after the file uploading is done.
To retrieve the Picture I have used a servlet and written the data to the OutputStream of the response. In a subsequent post I'll explain how to do it via a Java Bean, and a Custom Tag.
Here is the Servlet
showpicture.java
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class showpicture extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
String name=request.getParameter("picturename");
Context initcontext=new InitialContext();
Context envcontext=(Context)initcontext.lookup("java:/comp/env");
DataSource ds=(DataSource)envcontext.lookup("Pictures");
Connection con=ds.getConnection();
PreparedStatement ps=con.prepareStatement("select picture from pictures where picturename=?");
ps.setString(1,name);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
Blob b=rs.getBlob(1);
OutputStream out=response.getOutputStream();
InputStream in=b.getBinaryStream();
int n=in.read();
while(n!=-1)
{
out.write(n);
n=in.read();
}
out.flush();
out.close();
in.close();
con.close();
}
}
catch(Exception ex)
{
}
}
}
To display the Pictures in an HTML page use the img tag, and send the PictureName via a GET name value pair.
Here is the HTML Page
Pictures.html
<img src="showpicture?picturename=Champak.jpg" alt="Champak.jpg" width="300" height="300"/>
<img src="showpicture?picturename=design.jpg" alt="design.jpg" width="300" height="300"/>
web.xml
<web-app>
<servlet>
<servlet-name>MYFILE</servlet-name>
<servlet-class>servlets.uploaderservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MYFILE</servlet-name>
<url-pattern>/uploaderservlet/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>showimages</servlet-name>
<servlet-class>servlets.showpicture</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showimages</servlet-name>
<url-pattern>/showpicture/*</url-pattern>
</servlet-mapping>
</web-app>
Transferring Data and Pictures through a WCF Service from a MS SQL Server database.
In this Post I have explained a method to download a picture stored in a MS SQL Server database via a WCF Service. For uploading the picture to the database refer to my earlier post.
This example consists of Two parts a WCF Service and a WCF Client. Let's begin by first creating the required tables.
create table Pictures(PictureName varchar(50) primary key,Picture varbinary(max) not null)
Start a ASP.NET website in Visual Studio.Select WCF Service. Open Server Explorer and open the database. Create a DataSet and drag the table to the DataSet.
The PhotoServiceServer
This application comprises an interface IPhotoService. An Implementation PhotoService, PhotoService.svc, Web.config.
IPhotoService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IPhotoService
{
[OperationContract]
byte[] GetPhoto(string name);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class NameAndPhoto
{
byte[] photo;
string name;
public NameAndPhoto(byte[] photo, string name)
{
this.photo = photo;
this.name = name;
}
[DataMember]
public byte[] Picture
{
get { return photo ; }
set { photo = value; }
}
[DataMember]
public string Name
{
get { return name ; }
set { name =value ; }
}
}
PhotoService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class PhotoService : IPhotoService
{
private DataSet1TableAdapters.PicturesTableAdapter da = new DataSet1TableAdapters.PicturesTableAdapter();
public byte[] GetPhoto(string name)
{
return da.GetPicture(name);
}
public NameAndPhoto GetPhotoAndName(string name)
{
DataSet1.PicturesDataTable dt = da.GetPictureAndName(name);
DataSet1.PicturesRow dr = (DataSet1.PicturesRow)dt.Rows[0];
return new NameAndPhoto(dr.Picture, dr.PictureName);
}
}
PhotoService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="PhotoService" CodeBehind="~/App_Code/Service.cs" %>
Web.config
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="HypatiaConnectionString" connectionString="Data Source=.\hypatia;Initial Catalog=Hypatia;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<system.serviceModel>
<services>
<service name="PhotoService" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="IPhotoService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The PhotoServiceClient
This is again a website which will connect to the WCF Server and retrieve the results. First of all we need to establish a Service Reference to the WCF Service. Run the WCF Service and from the browser copy the URL. Place it in the ServiceReference Dialog Box. This will create and store a Service Reference to be used by the Client. Create an object of the Service Client and call the methods. In this Post I have used only the GetPhoto method. I'll use the composite class in a separate Post.
Here are the Files on the Client.
configuration.svcinfo
<?xml version="1.0" encoding="utf-8"?>
<configurationSnapshot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:xml-wcfconfigurationsnapshot">
<behaviors />
<bindings>
<binding digest="System.ServiceModel.Configuration.WSHttpBindingElement, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089:<?xml version="1.0" encoding="utf-16"?><Data hostNameComparisonMode="StrongWildcard" messageEncoding="Text" name="WSHttpBinding_IPhotoService" textEncoding="utf-8" transactionFlow="false"><readerQuotas maxArrayLength="16384" maxBytesPerRead="4096" maxDepth="32" maxNameTableCharCount="16384" maxStringContentLength="8192" /><reliableSession enabled="false" inactivityTimeout="00:10:00" ordered="true" /><security mode="Message"><message algorithmSuite="Default" clientCredentialType="Windows" establishSecurityContext="true" negotiateServiceCredential="true" /><transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /></security></Data>" bindingType="wsHttpBinding" name="WSHttpBinding_IPhotoService" />
</bindings>
<endpoints>
<endpoint normalizedDigest="<?xml version="1.0" encoding="utf-16"?><Data address="http://localhost:1500/PhotoServiceServer/PhotoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPhotoService" contract="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService"><identity><dns value="localhost" /></identity></Data>" digest="<?xml version="1.0" encoding="utf-16"?><Data address="http://localhost:1500/PhotoServiceServer/PhotoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPhotoService" contract="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService"><identity><dns value="localhost" /></identity></Data>" contractName="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService" />
</endpoints>
</configurationSnapshot>
PhotoService.disco
<?xml version="1.0" encoding="utf-8"?>
<discovery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/disco/">
<contractRef ref="http://localhost:1500/PhotoServiceServer/PhotoService.svc?wsdl" docRef="http://localhost:1500/PhotoServiceServer/PhotoService.svc" xmlns="http://schemas.xmlsoap.org/disco/scl/" />
</discovery>
GetPhotos.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class GetPhotos : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Image1.ImageUrl = "~/ViewPictures.aspx?name=" + Server.UrlEncode(txtName.Text);
}
}
GetPhotos.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetPhotos.aspx.cs" Inherits="GetPhotos" %>
<!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>
<style type="text/css">
.style1
{
width: 700px;
border-style: solid;
border-width: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<center >
<table class="style1">
<tr>
<td colspan="2">
<asp:Label ID="lbl" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
Name</td>
<td>
<asp:TextBox ID="txtName" runat="server" Width="184px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Picture</td>
<td>
<asp:Image ID="Image1" runat="server" Height="104px" Width="130px" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Get Picture" />
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
ViewPictures.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
private WCFPhotoService.PhotoServiceClient photoclient = new WCFPhotoService.PhotoServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
try
{
string name = Request.QueryString["name"];
byte[] b = photoclient.GetPhoto(name);
Response.BinaryWrite(b);
}
catch
{
}
}
}
ViewPictures.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewPictures.aspx.cs" Inherits="_Default" %>
<!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>View Pictures</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
web.config
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPhotoService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1500/PhotoServiceServer/PhotoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPhotoService" contract="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
This example consists of Two parts a WCF Service and a WCF Client. Let's begin by first creating the required tables.
create table Pictures(PictureName varchar(50) primary key,Picture varbinary(max) not null)
Start a ASP.NET website in Visual Studio.Select WCF Service. Open Server Explorer and open the database. Create a DataSet and drag the table to the DataSet.
The PhotoServiceServer
This application comprises an interface IPhotoService. An Implementation PhotoService, PhotoService.svc, Web.config.
IPhotoService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IPhotoService
{
[OperationContract]
byte[] GetPhoto(string name);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class NameAndPhoto
{
byte[] photo;
string name;
public NameAndPhoto(byte[] photo, string name)
{
this.photo = photo;
this.name = name;
}
[DataMember]
public byte[] Picture
{
get { return photo ; }
set { photo = value; }
}
[DataMember]
public string Name
{
get { return name ; }
set { name =value ; }
}
}
PhotoService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class PhotoService : IPhotoService
{
private DataSet1TableAdapters.PicturesTableAdapter da = new DataSet1TableAdapters.PicturesTableAdapter();
public byte[] GetPhoto(string name)
{
return da.GetPicture(name);
}
public NameAndPhoto GetPhotoAndName(string name)
{
DataSet1.PicturesDataTable dt = da.GetPictureAndName(name);
DataSet1.PicturesRow dr = (DataSet1.PicturesRow)dt.Rows[0];
return new NameAndPhoto(dr.Picture, dr.PictureName);
}
}
PhotoService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="PhotoService" CodeBehind="~/App_Code/Service.cs" %>
Web.config
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="HypatiaConnectionString" connectionString="Data Source=.\hypatia;Initial Catalog=Hypatia;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<system.serviceModel>
<services>
<service name="PhotoService" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="IPhotoService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The PhotoServiceClient
This is again a website which will connect to the WCF Server and retrieve the results. First of all we need to establish a Service Reference to the WCF Service. Run the WCF Service and from the browser copy the URL. Place it in the ServiceReference Dialog Box. This will create and store a Service Reference to be used by the Client. Create an object of the Service Client and call the methods. In this Post I have used only the GetPhoto method. I'll use the composite class in a separate Post.
Here are the Files on the Client.
configuration.svcinfo
<?xml version="1.0" encoding="utf-8"?>
<configurationSnapshot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:xml-wcfconfigurationsnapshot">
<behaviors />
<bindings>
<binding digest="System.ServiceModel.Configuration.WSHttpBindingElement, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089:<?xml version="1.0" encoding="utf-16"?><Data hostNameComparisonMode="StrongWildcard" messageEncoding="Text" name="WSHttpBinding_IPhotoService" textEncoding="utf-8" transactionFlow="false"><readerQuotas maxArrayLength="16384" maxBytesPerRead="4096" maxDepth="32" maxNameTableCharCount="16384" maxStringContentLength="8192" /><reliableSession enabled="false" inactivityTimeout="00:10:00" ordered="true" /><security mode="Message"><message algorithmSuite="Default" clientCredentialType="Windows" establishSecurityContext="true" negotiateServiceCredential="true" /><transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /></security></Data>" bindingType="wsHttpBinding" name="WSHttpBinding_IPhotoService" />
</bindings>
<endpoints>
<endpoint normalizedDigest="<?xml version="1.0" encoding="utf-16"?><Data address="http://localhost:1500/PhotoServiceServer/PhotoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPhotoService" contract="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService"><identity><dns value="localhost" /></identity></Data>" digest="<?xml version="1.0" encoding="utf-16"?><Data address="http://localhost:1500/PhotoServiceServer/PhotoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPhotoService" contract="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService"><identity><dns value="localhost" /></identity></Data>" contractName="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService" />
</endpoints>
</configurationSnapshot>
PhotoService.disco
<?xml version="1.0" encoding="utf-8"?>
<discovery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/disco/">
<contractRef ref="http://localhost:1500/PhotoServiceServer/PhotoService.svc?wsdl" docRef="http://localhost:1500/PhotoServiceServer/PhotoService.svc" xmlns="http://schemas.xmlsoap.org/disco/scl/" />
</discovery>
GetPhotos.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class GetPhotos : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Image1.ImageUrl = "~/ViewPictures.aspx?name=" + Server.UrlEncode(txtName.Text);
}
}
GetPhotos.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetPhotos.aspx.cs" Inherits="GetPhotos" %>
<!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>
<style type="text/css">
.style1
{
width: 700px;
border-style: solid;
border-width: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<center >
<table class="style1">
<tr>
<td colspan="2">
<asp:Label ID="lbl" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
Name</td>
<td>
<asp:TextBox ID="txtName" runat="server" Width="184px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Picture</td>
<td>
<asp:Image ID="Image1" runat="server" Height="104px" Width="130px" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Get Picture" />
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
ViewPictures.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
private WCFPhotoService.PhotoServiceClient photoclient = new WCFPhotoService.PhotoServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
try
{
string name = Request.QueryString["name"];
byte[] b = photoclient.GetPhoto(name);
Response.BinaryWrite(b);
}
catch
{
}
}
}
ViewPictures.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewPictures.aspx.cs" Inherits="_Default" %>
<!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>View Pictures</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
web.config
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPhotoService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1500/PhotoServiceServer/PhotoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPhotoService" contract="WCFPhotoService.IPhotoService" name="WSHttpBinding_IPhotoService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
Subscribe to:
Posts (Atom)