OpenFileDialog in SilverLight? - 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;
}
}
}
}
}
}

Related

WinForm not work properly with fonts embedded resources

The embedded resource font is not working properly on the controls.
But it can is used by Graphics object draw something.
First, add fontawesome-webfont.ttf font file with embedded resource.
Then, get font from assembly resources.
Next, assign the font property to the control.
Code here:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Sample
{
public partial class FormSample : Form
{
PrivateFontCollection pfc;
Font font ;
public FormSample()
{
InitializeComponent();
pfc = LoadFontFromResource("Sample.assets.fontawesome-webfont.ttf");
font = new Font(pfc.Families[0], 16, FontStyle.Regular);
this.textBoxControl1.Text = "\uf028 fontawesome";
this.label1.Text = "\uf028 fontawesome";
this.label1.ForeColor = Color.Green;
this.textBoxControl1.ForeColor = Color.Green;
this.label1.Font = font;
this.textBoxControl1.Font = font;
}
private void button1_Click(object sender, EventArgs e)
{
this.label1.Font = font;
this.textBoxControl1.Font = font;
Graphics g = this.CreateGraphics();
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawString("\uf028 fontawesome(GDI+)", font, new SolidBrush(Color.Green), new Point(this.label1.Location.X+10, 80));
g.Dispose();
}
/// <summary>
/// Loads the font from resource.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>PrivateFontCollection.</returns>
public static PrivateFontCollection LoadFontFromResource(string name)
{
PrivateFontCollection pfc = new PrivateFontCollection();
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(name))
{
if (stream == null) return null;
byte[] fontData = new byte[stream.Length];
stream.Read(fontData, 0, (int)stream.Length);
IntPtr ptr = Marshal.AllocHGlobal(fontData.Length);
Marshal.Copy(fontData, 0, ptr, fontData.Length);
pfc.AddMemoryFont(ptr, fontData.Length);
return pfc;
}
}
}
}
This is helpful:Embedded resource font in C# does not work correctly,thanks.

progress bar is updated after reaching 100% in c#

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");
}
}

What's wrong with this code while writing or reading object on text file?

I want to write object on text file. Below is the code. Can anyone helps to find out the error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TestObjectWritingInTextfile
{
class Program
{
static void Main(string[] args)
{
Test t = new Test("Salma Mushtaq","61488");
List<Test> list = new List<Test>();
list.Add(t);
FileStream file1 = new FileStream(#"C:\Users\Mani\Desktop\Files\testing.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(file1);
sw.WriteLine(t); // Here I want to write object
FileStream file2 = new FileStream(#"C:\Users\Mani\Desktop\Files\testing.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(file2);
List<Test> l = sr.ReadLine();
sr.Close();
}
}
class Test
{
public string name;
public string phone;
public Test(string n, string p) {
this.name = n;
this.phone = p;
}
}
}
When I want to read object from text file, It shows unexpected errors.

Need to click on a button in iFrame page

I am trying to click on "btnPunch". This button is located in an iFrame. I am unable to make this work. I have used the Selenium IDE to record this button being clicked and created a DLL that also runs this process in NUnit without a problem. Any help would be appreciated after three months of working on this.
Thank you
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using NUnit.Framework;
using Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium;
namespace TimeClockEntry
{
public partial class PNow : Form
{
IWebDriver driver = new InternetExplorerDriver();
//driver = new InternetExplorerDriver();
//private ISelenium selenium;
//private StringBuilder verificationErrors;
//public void SetupTest()
//{
// selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://ew23.ultipro.com/");
// selenium.Start();
// verificationErrors = new StringBuilder();
//}
int linkcount = 0;
string userName;
string passWord;
public PNow()
{
InitializeComponent();
webBrowser1.Navigate("https://ew23.ultipro.com/login.aspx");
}
private void PNow_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
userName = Properties.Settings.Default.userName;
passWord = Properties.Settings.Default.passWord;
}
private void PNow_FormClosed(object sender, FormClosedEventArgs e)
{
this.Hide();
welcome f1 = new welcome();
f1.ShowDialog();
this.Close();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.Focus();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
linkcount++;
if (linkcount == 1)
{
webBrowser1.Document.GetElementById("ctl00_Content_Login1_UserName").SetAttribute("value", userName);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_Password").SetAttribute("value", passWord);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_LoginButton").InvokeMember("click");
}
if (linkcount == 2)
{
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
}
if (linkcount == 3)
{
// driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
this.Close();
}
}
}
}
You can try this also:-
if (linkcount == 3)
{
WebElement frameSwitch = driver.findElement(By.xpath("Xpath of iframe")); //Frame Xpath
driver.switchTo().frame(frameSwitch);
driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
driver.switchTo().defaultContent();
this.Close();
}
Try this.
if (linkcount == 3)
{
//get back to basic html source.
driver.SwitchTo().DefaultContent();
//switch to new frame
driver.SwitchTo().Frame("<FRAME NAME OR ID>");
driver.FindElement(By.Id("btnPunch")).Click();
}

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