progress bar is updated after reaching 100% in c# - winforms

I am working on file transfer software. But progress bar shows 100% directly not showing actual progress. So do i need to change my method to write file. Or there is some silly mistake. Here is my code.
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.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using System.Threading;
namespace Sender2
{
public partial class Form1 : Form
{
private Thread thrDownload;
private static int PercentProgress;
private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
public Form1()
{
InitializeComponent();
}
private void Browse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtSelectFilePath.Text = openFileDialog1.FileName;
String path1=txtSelectFilePath.Text;
files_list.Items.Add(path1);
files_list.View = View.List;
}
}
private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
{
PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
progressBar1.Value = PercentProgress;
lblProgress.Text = "Downloaded " + BytesRead + " out of " + TotalBytes + " (" + PercentProgress + "%)";
}
private void Send_Click(object sender, EventArgs e)
{
TransferService2.TransferService2Client client = new TransferService2.TransferService2Client();
foreach(ListViewItem item in files_list.Items)
{
TransferService2.File file = client.DownloadDocument(item.Text);
System.IO.FileStream fs = new System.IO.FileStream(#"c:\DownloadedFiles\" + file.Name, System.IO.FileMode.Create);
Int64 fileSize = file.Content.Length;
int bytesSize = 0;
byte[] downBuffer = new byte[2048];
int pos = 0;
int length = 128;
while (pos < file.Content.Length)
{
if (length > (file.Content.Length - pos))
{
length = file.Content.Length - pos;
}
fs.Write(file.Content, pos, length);
this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { file.Content.Length, fileSize });
pos = pos + length;
}
MessageBox.Show(file.Name + " is downloaded");
}
}
}
}
TransferService2.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TransferService2
{
public class TransferService2 : ITransferService2
{
public File DownloadDocument(String filepath)
{
File file = new File();
String path = filepath;
byte[] buffer;
FileStream fs = new FileStream(#path, FileMode.Open, FileAccess.Read);
try
{
int length = (int)fs.Length;
buffer = new byte[length];
int count;
int sum = 0;
while((count=fs.Read(buffer,sum,length-sum))>0)
{
sum = sum + count;
}
}
finally
{
fs.Close();
}
file.Content = buffer;
file.Name = Path.GetFileName(path);
return file;
}
}
}
ITransferService2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TransferService2
{
[ServiceContract]
public interface ITransferService2
{
[OperationContract]
File DownloadDocument(String filepath);
}
[DataContract]
public class File
{
[DataMember]
public string Name { get; set; }
[DataMember]
public byte[] Content { get; set; }
}
}

As I mentioned in the comments, you are performing the whole operation synchronously on the UI thread, hence it's busy and cannot update during the processing.
You need to let the operation execute asynchronously. There are many ways to do that, here is one possible way using async/await:
private async void Send_Click(object sender, EventArgs e)
{
TransferService2.TransferService2Client client = new TransferService2.TransferService2Client();
foreach(ListViewItem item in files_list.Items)
{
TransferService2.File file = await Task.Run(() => client.DownloadDocument(item.Text));
System.IO.FileStream fs = new System.IO.FileStream(#"c:\DownloadedFiles\" + file.Name, System.IO.FileMode.Create);
Int64 fileSize = file.Content.Length;
int bytesSize = 0;
byte[] downBuffer = new byte[2048];
int pos = 0;
int length = 128;
while (pos < file.Content.Length)
{
if (length > (file.Content.Length - pos))
{
length = file.Content.Length - pos;
}
await fs.WriteAsync(file.Content, pos, length);
// Here the await will resume on the UI thread, so no Invoke is needed
pos = pos + length;
this.UpdateProgress(pos, fileSize);
}
MessageBox.Show(file.Name + " is downloaded");
}
}

Related

Convert Spellbox to a RichTextBox

Hans Passant has code that adds a textbox based spellbox for spell checking in WinForms app. It works great but I would like to know if it could be converted to a RichTextBox so that I could add bolding, color, etc.
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Forms.Design;
[Designer(typeof(ControlDesigner))]
//[DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
class SpellBox : ElementHost
{
public SpellBox()
{
// string templatePath = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Documents\\AviationMaintenanceLogger\\Templates\\";
box = new TextBox();
base.Child = box;
box.TextChanged += (s, e) => OnTextChanged(EventArgs.Empty);
Uri lex_file = new Uri(System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Documents\\AviationMaintenanceLogger\\Templates\\AML.lex");
box.SpellCheck.CustomDictionaries.Add(lex_file);
box.SpellCheck.IsEnabled = true;
box.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
this.WordWrap = true;
this.Size = new System.Drawing.Size(100, 20);
}
public override string Text
{
get { return box.Text; }
set { box.Text = value; }
}
[DefaultValue(false)]
public bool Multiline
{
get { return box.AcceptsReturn; }
set { box.AcceptsReturn = value; }
}
[DefaultValue(false)]
public bool WordWrap
{
get { return box.TextWrapping != TextWrapping.NoWrap; }
set { box.TextWrapping = value ? TextWrapping.Wrap : TextWrapping.NoWrap; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new System.Windows.UIElement Child
{
get { return base.Child; }
set { /* Do nothing to solve a problem with the serializer !! */ }
}
private TextBox box;
}
This is the new code that works:
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Forms.Design;
using System.Windows.Documents;
using System.Drawing;
[Designer(typeof(ControlDesigner))]
//[DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
class SpellBoxNew : ElementHost
{
public SpellBoxNew()
{
// string templatePath = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Documents\\AviationMaintenanceLogger\\Templates\\";
box = new RichTextBox();
base.Child = box;
box.IsReadOnly = false;
box.TextChanged += (s, e) => OnTextChanged(EventArgs.Empty);
Uri lex_file = new Uri(System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Documents\\AviationMaintenanceLogger\\Templates\\AML.lex");
box.SpellCheck.CustomDictionaries.Add(lex_file);
box.SpellCheck.IsEnabled = true;
box.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
//this.Font = new Font("Arial", 24,FontStyle.Bold);
// this.WordWrap = true;
this.Multiline = true;
this.Size = new System.Drawing.Size(100, 20);
}
[DefaultValue(false)]
public override string Text
{
get
{
// string richText = new TextRange(transcriberArea.Document.ContentStart, transcriberArea.Document.ContentEnd).Text;
string richText = new TextRange(box.Document.ContentStart, box.Document.ContentEnd).Text;
return richText;
}
set
{
box.Document.Blocks.Clear();
box.Document.Blocks.Add(new System.Windows.Documents.Paragraph(new Run(value)));
}
}
public bool Multiline
{
get { return box.AcceptsReturn; }
set { box.AcceptsReturn = value; }
}
[DefaultValue(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new System.Windows.UIElement Child
{
get { return base.Child; }
set { /* Do nothing to solve a problem with the serializer !! */ }
}
private RichTextBox box;

When debuging the window doesn't appear

`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Server_chat
{
class server
{
private static int myProt = 10000;
private static byte[] buf2 = new byte[1024];
private static Socket serverSocket;
private static string message2;
/// <summary>
/// server socket
/// </summary>
public void Server_run()
{
IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
IPAddress ip = ipHost.AddressList[0];
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip,Program.form1.localport));
serverSocket.Listen(10);
Program.form1.myscan_box = "启动监听成功 !!";
Thread myThread = new Thread(ListenClientConnect);
myThread.IsBackground = true;
myThread.Start();
}
/// <summary>
/// 监听客户端连接
/// </summary>
private static void ListenClientConnect()
{
while (true) // 点对点通信
{
Socket clientSocket = serverSocket.Accept();
if (clientSocket.Connected == true)
{
IPEndPoint client_endpoint = (IPEndPoint)clientSocket.RemoteEndPoint;
Program.form1.myclientip_box = client_endpoint.Address.ToString() + "\\" + client_endpoint.Port.ToString();
Program.form1.myscan_box = "连接客户端 " + client_endpoint.Address.ToString() + " 成功 !!";
//服务端接收线程
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.IsBackground = true;
receiveThread.Start(clientSocket);
//服务端发送线程
Thread sendThread = new Thread(SendMessage);
sendThread.IsBackground = true;
sendThread.Start(clientSocket);
break;
}
}
}
/// <summary>
/// receive message
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
int len = myClientSocket.Receive(buf2);
message2 = Encoding.ASCII.GetString(buf2).Substring(0, len);
IPEndPoint client_endpoint = (IPEndPoint)myClientSocket.RemoteEndPoint;
Program.form1.myscan_box = client_endpoint.Address +": "+ message2;
}
catch (Exception ex)
{
Program.form1.myscan_box = ex.Message;
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
/// <summary>
/// send message
/// </summary>
/// <param name="clientSocket"></param>
private static void SendMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
if (Program.form1.send_flag11 == 1)
{
myClientSocket.Send(Encoding.ASCII.GetBytes(Program.form1.message11));
Program.form1.send_flag11 = 0;
}
}
}
}
}
`When starting or debugging my program the window doesn't appear. But vs2012 suggests the debug session is ready.
When startting the program, the window appears but a popup window with the message "the program has stopped working, choose to debug or stop".
What's the problem? What should I do?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Threading;
namespace Server_chat
{
public partial class Form1 : Form
{
public string localip;
public int localport = 10002;
public string s_sendMessage;
public static int send_flag = 0;
public string message11
{
get { return s_sendMessage; }
}
public int send_flag11
{
get { return send_flag; }
set { send_flag = value; }
}
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
localip = ipAddr.ToString();
myip_box.Text = localip;
port_box.Text = localport.ToString();
server myserver = new server();
Thread th_server = new Thread(myserver.Server_run);
th_server.IsBackground = true;
th_server.Start();
}
private void setting_btn_Click(object sender, EventArgs e)
{
localport = Int16.Parse(port_box.Text);
scan_box.AppendText("\r\n" + "端口改成: " + port_box.Text);
}
private void send_btn_Click(object sender, EventArgs e)
{
s_sendMessage = chat_box.Text;
chat_box.Text = "";
scan_box.AppendText(s_sendMessage + "\r\n");
send_flag = 1;
}
}
}

Silverlight Pixel Perfect Collsion Detection

I am working on a project for my Uni, and I am currently stuck on a Pixel Perfect Collision Detection from this website http://www.andybeaulieu.com/Home/tabid/67/EntryID/160/Default.aspx. I have downloded example project that is using this collsion detection and it is working fine even with my own pictures. I have done the same thing in my project and it is not working. Here is the link to my app: https://www.cubby.com/pl/LostInTheMath.zip/_dd23e2c827604c068a3fe63ff42d22b2 could anyone tell me whats wrong with it? Thank you.
Here is the main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
namespace LostInTheMath
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}
private void UserCntrl_MouseMove(object sender, MouseEventArgs e)
{
Point pt = e.GetPosition(cnvHitTest);
Monkey.SetValue(Canvas.LeftProperty, pt.X);
Monkey.SetValue(Canvas.TopProperty, pt.Y);
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
Image MonkeyShell = Monkey.FindName("imgMonkey") as Image;
Image Mazer = Maze.FindName("imgMaze") as Image;
if (CheckCollision(Monkey, MonkeyShell, Maze, Mazer))
{
Monkey.Width = 1000;
txtStatus.Text = "Collision with XAML Element!";
return;
}
txtStatus.Text = string.Empty;
}
private bool CheckCollision(FrameworkElement control1, FrameworkElement controlElem1, FrameworkElement control2, FrameworkElement controlElem2)
{
// first see if sprite rectangles collide
Rect rect1 = UserControlBounds(control1);
Rect rect2 = UserControlBounds(control2);
rect1.Intersect(rect2);
if (rect1 == Rect.Empty)
{
// no collision - GET OUT!
return false;
}
else
{
bool bCollision = false;
Point ptCheck = new Point();
// NOTE that creating the writeablebitmap is a bit intense
// so we will do this once and store results in Tag property
// in a real game, you might abstract this into a Sprite class.
if (controlElem1 is Image)
controlElem1.Tag = GetWriteableBitmap(control1);
if (controlElem2 is Image)
controlElem2.Tag = GetWriteableBitmap(control2);
// now we do a more accurate pixel hit test
for (int x = Convert.ToInt32(rect1.X); x < Convert.ToInt32(rect1.X + rect1.Width); x++)
{
for (int y = Convert.ToInt32(rect1.Y); y < Convert.ToInt32(rect1.Y + rect1.Height); y++)
{
ptCheck.X = x;
ptCheck.Y = y;
if (CheckCollisionPoint(ptCheck, control1, controlElem1))
if (CheckCollisionPoint(ptCheck, control2, controlElem2))
{
bCollision = true;
break;
}
}
if (bCollision) break;
}
return bCollision;
}
}
public bool CheckCollisionPoint(Point pt, FrameworkElement control, FrameworkElement controlElem)
{
if (controlElem is Image)
{
// NOTE that we saved the WB in the Tag object for performance.
// in a real app, you might abstract this in your sprite class.
WriteableBitmap wb = controlElem.Tag as WriteableBitmap;
int width = wb.PixelWidth;
int height = wb.PixelHeight;
double offSetX = Convert.ToDouble(control.GetValue(Canvas.LeftProperty));
double offSetY = Convert.ToDouble(control.GetValue(Canvas.TopProperty));
pt.X = pt.X - offSetX;
pt.Y = pt.Y - offSetY;
int offset = Convert.ToInt32((width * pt.Y) + pt.X);
return (wb.Pixels[offset] != 0);
}
else
{
List<UIElement> hits = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(pt, controlElem) as List<UIElement>;
return (hits.Contains(controlElem));
}
}
private WriteableBitmap GetWriteableBitmap(FrameworkElement control)
{
WriteableBitmap wb = new WriteableBitmap((int)control.Width, (int)control.Height); ;
wb.Render(control, new TranslateTransform());
wb.Invalidate();
return wb;
}
public Rect UserControlBounds(FrameworkElement control)
{
Point ptTopLeft = new Point(Convert.ToDouble(control.GetValue(Canvas.LeftProperty)), Convert.ToDouble(control.GetValue(Canvas.TopProperty)));
Point ptBottomRight = new Point(Convert.ToDouble(control.GetValue(Canvas.LeftProperty)) + control.Width, Convert.ToDouble(control.GetValue(Canvas.TopProperty)) + control.Height);
return new Rect(ptTopLeft, ptBottomRight);
}
}
}

OpenFileDialog in SilverLight?

I have download the code for OpenFileDialog (File Upload function) from Silverlight tutorials website. I am creating a silverlight application using ESRI API and I would like to incorporate the file upload functionality in to it. I have replicated the exact code in to my application there are no errors when I run it, but for some reason my application dosen't execute this line of code "c.OpenWriteAsync(Ub.Uri)"
Edit 2: I notice another thing when I upgraded the general handler (receiver.ashx) which I downloaded it has the following as first line while my generic handler doesn't
<%# WebHandler Language="C#" Class="receiver" %>
I dont know why my code dosent trigger it :(
Here is my Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Markup;
using System.Windows.Shapes;
using System.ComponentModel;
using ESRI.ArcGIS.Client;
using System.Windows.Controls.Primitives;
using System.IO;
using System.IO.IsolatedStorage;
namespace DataTool
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// HtmlPage.RegisterScriptableObject("SilverlightLearn", this);
}
[ScriptableMember]
private void btnService_Click(object sender, RoutedEventArgs e)
{
}
private void btnUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog Dialog = new OpenFileDialog();
Dialog.Multiselect = false;
Dialog.Filter = "All Files|*.*";
bool? SelFil = Dialog.ShowDialog();
if (SelFil != null && SelFil == true)
{
string selectedfilename = Dialog.File.Name;
UploadFile(selectedfilename, Dialog.File.OpenRead());
}
else
{
//do something else
}
}
private void StoreIso(string fileName, Stream data)
{
}
private void UploadFile(string fileName, System.IO.Stream data)
{
// WebClient Wbc = new WebClient();
UriBuilder Ub = new UriBuilder("http://localhost:63461/DataTool/datareceiver.ashx");
Ub.Query = string.Format("filename={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
c.OpenWriteAsync(Ub.Uri);
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
Here is my datareceiver.ashx code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace DataTool.Web
{
/// <summary>
/// Summary description for datareceiver
/// </summary>
public class datareceiver : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
public void SaveFile(Stream st, FileStream fs)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = st.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I have gone through the downloaded sample code and my code STEP BY STEP and found that my code dosent execute the OpenWriteAsync statement. The downloaded code was in .net 3.5 or 3.0 framework and I upgraded it to 4.0.
EDIT:
Please find a sample here https://rapidshare.com/files/459667631/Testing.zip
This is simple , check following code
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
using (StreamReader reader = dlg.SelectedFile.OpenText())
// Store file content in 'text' variable
string text = reader.ReadToEnd();
}
}
C# Example 2: Copy files to the application's isolated storage.
using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
...
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All files (*.*)|*.*";
dlg.EnableMultipleSelection = true;
if (dlg.ShowDialog() == DialogResult.OK) {
// Save all selected files into application's isolated storage
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
foreach (FileDialogFileInfo file in dlg.SelectedFiles) {
using (Stream fileStream = file.OpenRead()) {
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(file.Name, FileMode.Create, iso)) {
// Read and write the data block by block until finish
while(true) {
byte[] buffer = new byte[100001];
int count = fileStream.Read(buffer, 0, buffer.Length);
if (count > 0) {
isoStream.Write(buffer, 0, count);
}
else {
break;
}
}
}
}
}
}

Is there a way for printing a report without previewing it on report viewer?

I want to print a report (RDL) directly without previewing it. Is there a solution for this work?
So I think you want to print a Report without Preview so check this out
http://msdn.microsoft.com/en-us/library/ms252091.aspx
in that article youfind following code
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
public class Demo : IDisposable
{
private int m_currentPageIndex;
private IList<Stream> m_streams;
private DataTable LoadSalesData()
{
// Create a new DataSet and read sales data file
// data.xml into the first DataTable.
DataSet dataSet = new DataSet();
dataSet.ReadXml(#"..\..\data.xml");
return dataSet.Tables[0];
}
// Routine to provide to the report renderer, in order to
// save an image for each page of the report.
private Stream CreateStream(string name,string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
{
Stream stream = new FileStream(#"..\..\" + name +
"." + fileNameExtension, FileMode.Create);
m_streams.Add(stream);
return stream;
}
// Export the given report as an EMF (Enhanced Metafile) file.
private void Export(LocalReport report)
{
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
m_streams = new List<Stream>();
report.Render("Image", deviceInfo, CreateStream,
out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
// Handler for PrintPageEvents
private void PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = new
Metafile(m_streams[m_currentPageIndex]);
ev.Graphics.DrawImage(pageImage, ev.PageBounds);
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
private void Print()
{
const string printerName =
"Microsoft Office Document Image Writer";
if (m_streams == null || m_streams.Count == 0)
return;
PrintDocument printDoc = new PrintDocument();
printDoc.PrinterSettings.PrinterName = printerName;
if (!printDoc.PrinterSettings.IsValid)
{
string msg = String.Format(
"Can't find printer \"{0}\".", printerName);
MessageBox.Show(msg, "Print Error");
return;
}
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
printDoc.Print();
}
// Create a local report for Report.rdlc, load the data,
// export the report to an .emf file, and print it.
private void Run()
{
LocalReport report = new LocalReport();
report.ReportPath = #"..\..\Report.rdlc";
report.DataSources.Add(
new ReportDataSource("Sales", LoadSalesData()));
Export(report);
m_currentPageIndex = 0;
Print();
}
public void Dispose()
{
if (m_streams != null)
{
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}
public static void Main(string[] args)
{
using (Demo demo = new Demo())
{
demo.Run();
}
}
}

Resources