I want to use openfiledialog to upload file,but when I write following code Security exception is fired that is "Dialogs must be user-initiated."
btn_click()
{
OpenFileDialog fileDialog=new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Filter = "All Files|*.*";
bool? retval = fileDialog.ShowDialog();
if (fileDialog.ShowDialog()==false){
Stream strm = fileDialog.File.OpenRead();
byte[] Buffer = new byte[strm.Length];
strm.Read(Buffer, 0, (int)strm.Length);
strm.Dispose();
strm.Close();
Uploadfile file=new Uploadfile();
file.FileName = fileDialog.File.Name;
file.File = Buffer;
po.fileUploadAsync(file);
}
As the exception you're getting states the open file dialog can only be activated from a user initiated action when the application is run in the browser and with restricted trust.
What are you trying to achieve?
The simplest solution is to add a button to your UI that allows the user to control when this process happens.
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();
}
}
Related
I am making excel report of my SQL server table records. In Asp page grid view I am fetching required data then this data is downloaded in excel. one column has hyperlink value & I need this hyperlink should only work in Asp page Grid view but after download, it should redirect to a new page where Unauthorized access error will be shown. I am not getting how to show unauthorized error link in excel file hyperlink click.
Here is my code
protected void LnkBtnViewImage_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
LinkButton lnkbtimage = sender as LinkButton;
GridViewRow gvrowreport = lnkbtimage.NamingContainer as GridViewRow;
//int Exhid = Convert.ToInt32(gvrowreport.Cells[1].Text);
string Exhid = ((HiddenField)gvrowreport.Cells[0].FindControl("HiddenField1")).Value;
SqlCommand cmd = new SqlCommand("select ImageName,ImageData from CompanyImage where Edition_Id='" + Session["Edition_ID"].ToString() + "' and Exhibitor_ID=#Exhibitor_ID ", con);
cmd.Parameters.AddWithValue("#Exhibitor_ID", Exhid);
//Select Statement con
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr!=null)
{
dr.Read();
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//string filePath = GridViewLogo.DataKeys[gvrow.RowIndex].Value.ToString();
//if (!Convert.IsDBNull(dr["ImageData"]))
//{
Response.ContentType = "application/vnd.ms-jpg";
//to open file prompt Box open or Save file
Response.AddHeader("content-disposition", "attachment;filename=" + dr["ImageName"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["ImageData"]);
Response.End();
//}
//else
//{
// //lblhid.Text = "Image is not uploaded here !!";
// //lblhid.ForeColor = Color.Green;
// //lblhid.Visible = true;
// //// lblhexcelerror.Visible = false;
// //gvrow.Visible = false;
//}
}
else
{
//LinkButton lnkbtn = sender as LinkButton;
//GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//gvrow.Visible = false;
}
con.Close();
With a few specific exceptions (e.g. forms with CSRF tokens) it's usually the case that when you click on a link the server doesn't care how you got there, it receives the request and serves the requested page or resource. It doesn't really know whether the link was contained within an Excel file, or another HTML document, an email etc. That's one of the clever things about hyperlinks, in fact.
Even if what you were suggesting was feasible, there would be nothing to stop a user from copying and pasting it into their browser and accessing it from there.
If you don't want this link to work from your Excel document, and/or you don't want users to be given the link, the simplest thing would be not to include it in the document in the first place.
Also if it's the case that this link is being given to users who shouldn't have access to whatever is shown the link, then simply not giving them the link ("security by obscurity") is not really adequate protection. If that's the situation then you need to think about how access to that link is authorised, no matter where the user acquired the knowledge of it.
use trim in code of reports.
In trim you have to remove "mailto:" while exporting it to the excel
I use Xamarin Android. I have a PDF File stored in Assets folder from Xamarin Android.
I want to share this file in WhatsApp, but I receive the message:
The file you picked was not a document.
I tried two ways:
This is the first way
var SendButton = FindViewById<Button>(Resource.Id.SendButton);
SendButton.Click += (s, e) =>
{
////Create a new file in the exteranl storage and copy the file from assets folder to external storage folder
Java.IO.File dstFile = new Java.IO.File(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");
dstFile.CreateNewFile();
var inputStream = new FileInputStream(Assets.OpenFd("my-pdf-File--2017.pdf").FileDescriptor);
var outputStream = new FileOutputStream(dstFile);
CopyFile(inputStream, outputStream);
//to let system scan the audio file and detect it
Intent intent = new Intent(Intent.ActionMediaScannerScanFile);
intent.SetData(Uri.FromFile(dstFile));
this.SendBroadcast(intent);
//share the Uri of the file
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(dstFile));
sharingIntent.SetType("application/pdf");
this.StartActivity(Intent.CreateChooser(sharingIntent, "#string/QuotationShare"));
};
This is the second
//Other way
var SendButton2 = FindViewById<Button>(Resource.Id.SendButton2);
SendButton2.Click += (s, e) =>
{
Intent intent = new Intent(Intent.ActionSend);
intent.SetType("application/pdf");
Uri uri = Uri.Parse(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");
intent.PutExtra(Intent.ExtraStream, uri);
try
{
StartActivity(Intent.CreateChooser(intent, "Share PDF file"));
}
catch (System.Exception ex)
{
Toast.MakeText(this, "Error: Cannot open or share created PDF report. " + ex.Message, ToastLength.Short).Show();
}
};
In other way, when I share via email, the PDF file is sent empty (corrupt file)
What can I do?
The solution is copying de .pdf file from assets folder to a local storage. Then We able to share de file.
First copy the file:
string fileName = "my-pdf-File--2017.pdf";
var localFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var MyFilePath = System.IO.Path.Combine(localFolder, fileName);
using (var streamReader = new StreamReader(Assets.Open(fileName)))
{
using (var memstream = new MemoryStream())
{
streamReader.BaseStream.CopyTo(memstream);
var bytes = memstream.ToArray();
//write to local storage
System.IO.File.WriteAllBytes(MyFilePath, bytes);
MyFilePath = $"file://{localFolder}/{fileName}";
}
}
Then share the file, from local storage:
var fileUri = Android.Net.Uri.Parse(MyFilePath);
var intent = new Intent();
intent.SetFlags(ActivityFlags.ClearTop);
intent.SetFlags(ActivityFlags.NewTask);
intent.SetAction(Intent.ActionSend);
intent.SetType("*/*");
intent.PutExtra(Intent.ExtraStream, fileUri);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
var chooserIntent = Intent.CreateChooser(intent, title);
chooserIntent.SetFlags(ActivityFlags.ClearTop);
chooserIntent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(chooserIntent);
the file you picked was not a document
I had this issue when I trying to share a .pdf file via WhatsApp from assets folder, but it gives me the same error as your question :
the file you picked was not a document
Finally I got a solution that copy the .pdf file in assets folder to Download folder, it works fine :
var pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
Java.IO.File dstFile = new Java.IO.File(pathFile.AbsolutePath + "/my-pdf-File--2017.pdf");
Effect like this.
I'm using the code below to retrieve an attachment from a webserver. The client in this case is a web browser. So currently, the user makes a request to a webserver for the attachment. The webserver makes an MTOM request to another server for the attachment. That webserver then waits for the attachment to download before it begins writing that attachment out to the response. The user is waiting twice as long to get the file. How can I tap into the Axis2 code to get access to the temp file so that I can stream it to the user as it is being created? I know this doesn't sound like the best way to do this, but this is the requirement. I'm working with large files up to 2GB, so waiting twice as long to recieve the file isn't working out.
Options options = new Options();
options.setTo(new EndpointReference(this.endpointUrl));
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, Constants.VALUE_TRUE);
options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, this.tempDirectory);
options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, String.valueOf(this.tempFileSizeThreshold));
options.setTimeOutInMilliSeconds(this.serviceRequestTimeOut);
sender = new ServiceClient();
sender.setOptions(options);
OMElement result = sender.sendReceive(this.getAttachmentPayload(productId, attachmentId));
OMElement attachmentElement = result.getFirstElement();
Iterator<OMElement> elementIterator = attachmentElement.getChildElements();
String fileName = "";
DataHandler dataHandler = null;
while (elementIterator.hasNext()) {
OMElement element = elementIterator.next();
if (element.getQName().getLocalPart().equals("name")) {
fileName = element.getText();
} else if (element.getQName().getLocalPart().equals("attachment")) {
dataHandler = (DataHandler) ((OMText) element.getFirstOMChild()).getDataHandler();
}
}
org.w3.www._2005._05.xmlmime.Base64Binary b64data = ---YOUR_SOURCE_ATTACHMENT---;
org.apache.axiom.attachments.CachedFileDataSource ds = (CachedFileDataSource) b64data.getBase64Binary().getDataSource();
String absPath = ds.getFile().getAbsolutePath();
I have a document which is stored in doc library of sharepoint..now i want to open and read data from it ...how can i do it ..filestream does not take url as input ..please help.
Try SPFile.OpenBinaryStream
From SharePoint 2007 - Read content from SPFile:
string content = string.Empty;
using (SPSite oSite = new SPSite("http://localhost/"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPDocumentLibrary doclib = (SPDocumentLibrary)oWeb.GetList(DocLibUrl);
SPFile htmlFile = doclib.Items[0].File;
using (System.IO.StreamReader reader = new System.IO.StreamReader(htmlFile.OpenBinaryStream()))
{
content = reader.ReadToEnd();
}
}
}
Sounds like you need to use a HTTPRequest object to retrieve the file. Here is a code example:
http://geeknotes.wordpress.com/2008/01/10/saving-a-possibly-binary-file-from-a-url-in-c/
I want to create a windows form containing a linklable such that when user clicks on that linklable, a file with some format(for example a pdf file or html file) which is added to resources,opens.
it will not be opened in form,it means the file will be opened out of program with adobe reader or another program.
How can I do this?
Thank you
You'll have to extract this file from resources (I'm assuming we're talking assembly-embedded resources here) to %temp% and then just Process.Start() it. Make sure extracted file has proper extension, though.
You can do so using Process.Start:
System.Diagnostics.Process.Start(#"C:\myfolder\document.pdf");
If the file is an embedded resource, you would first have to extract it and save it to disc. You cannot open a document from a stream directly, because third-party applications won't be able to access your process' memory:
string resourceName = "test.pdf";
string filename = Path.Combine(Path.GetTempPath(), resourceName);
Assembly asm = typeof(Program).Assembly;
using (Stream stream = asm.GetManifestResourceStream(
asm.GetName().Name + "." + resourceName))
{
using (Stream output = new FileStream(filename,
FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] buffer = new byte[32 * 1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
}
Process.Start(filename);