I've got an oob app with a webbrowser on it.
The webbrowser source is databound with a URI defined by me. The URI has a path to a webpage from my server that displays a PDF file from its hardrive.
Note that all this is done on a local network.
URI example: uri = new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
Page code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string myURL = Request.Url.ToString();
string[] ParamArray = Regex.Split(myURL, "pdf=");
string Params = ParamArray[ParamArray.Length - 1];
if (Params.Length > 0)
{
Filename = Regex.Replace(Params, #"//", #"\\"); ;
if (File.Exists(Filename))
{
Response.ContentType = "Application/pdf";
Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream.
Response.End();
}
else
this.Title = "PDF Not Found";
}
}
protected void Page_Load(object sender, EventArgs e) { string myURL = Request.Url.ToString(); string[] ParamArray = Regex.Split(myURL, "pdf="); //If the URL has parameters, then get them. If not, return a blank string string Params = ParamArray[ParamArray.Length - 1]; if (Params.Length > 0) { //to the called (src) web page Filename = Regex.Replace(Params, #"//", #"\\"); ; if (File.Exists(Filename)) { Response.ContentType = "Application/pdf"; Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream. Response.End(); } else this.Title = "PDF Not Found"; } }
The first time I set the WebBrowser source everything it displays the PDF. But when I set the URI one second time the app throws an exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100).
I've done a few tests and here are the results:
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://www.google.com"); ->error
1º new Uri(#"http://www.google.com");
2º new Uri(#"http://www.microsoft.com");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
3º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
I also forgot to say that when running the app from my browser (using a HTMLHost) the pages display just fine. Opening the pages using a browser will also work well.
It must be some problem with my aspx page. Any ideas?
Pedro
I've managed to resolve this by creating a new browser for each page. If you know of a more elegant solution please share.
I am not sure if I'm following the question/problem correctly but maybe loading the pages async and then assigning to webbrowser? Forgive me if I am off-base here.
public void ShowLink(string linkUrl)
{
if (App.Current.IsRunningOutOfBrowser)
{
var pageRequest = new WebClient();
pageRequest.DownloadStringCompleted += pageRequest_DownloadStringCompleted;
pageRequest.DownloadStringAsync(new Uri(linkUrl, UriKind.Absolute));
}
}
void pageRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
webBrowserLink.NavigateToString(e.Result.ToString());
}
Related
My asp.net web page contain two textboxes one for URL and another for ImagePath
I want URL entered by user in following format
e.g http://articles.site.com in the URL textbox.If user enter URL other than http://articles.site.com this format it should not allowed.Message should display like Enter correct URL.
And for ImagePath entered by user ImagePath textbox like following manner.
e.g http://articles.site.com/ImageServer/Public/2016/July/EnglishBanner/effective-skunk-rinse-recipe.jpg
protected void Upload(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
In the Page Load event of the ASP.Net Web Page the files are fetched from the Images folder and then the fetched image files are bound to the ASP.Net GridView control
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "~/Images/" + fileName));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
you have use this function for validate url.
private bool IsUrlValid(string url)
{
string pattern = #"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$";
Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return reg.IsMatch(url);
}
I am developing a complaint form. In this this form, I must make a function that uploads a file and then delete the file that was uploaded. I can upload a file to the server, but I can't take a link of the file I upload to the server in order to delete it. Please help me. Here is my code:
public string FilePath;
protected void btAdd_Click(object sender, EventArgs e)
{
if (AttachFile.HasFile)
{
try
{
string[] sizes = {"B", "KB", "MB", "GB"};
double sizeinbytes = AttachFile.FileBytes.Length;
string filename = Path.GetFileNameWithoutExtension(AttachFile.FileName);
string fileextension = Path.GetExtension(AttachFile.FileName);
int order = 0;
while (sizeinbytes >= 1024 && order + 1 < sizes.Length)
{
order++;
sizeinbytes = sizeinbytes/1024;
}
string result = String.Format("{0:0.##} {1}", sizeinbytes, sizes[order]);
string encryptionFileName = EncrytionString(10);
FilePath = "Path" + encryptionFileName.Trim() + AttachFile.FileName.Trim();
AttachFile.SaveAs(FilePath);
}
catch (Exception ex)
{
lbMessage.Visible = true;
lbMessage.Text = ex.Message;
}
}
}
protected void btDelete_Click(object sender, EventArgs e)
{
try
{
File file = new FileInfo(FilePath);
if (file.Exists)
{
File.Delete(FilePath);
}
}
catch (FileNotFoundException fe)
{
lbMessage.Text = fe.Message;
}
catch (Exception ex)
{
lbMessage.Text = ex.Message;
}
}
Each request in asp.net creates a new object of your Page.
If you set variables during one request, they will not be available on the next request.
Your delete logic seems to depend upon FilePath being set during upload. If you want the page to remember that, keep it in the ViewState. The ViewState is maintained across requests to the same page and that would allow you to use the variable FilePath during delete.
This can be easily achieved by making FilePath a property and getting it from the ViewState.
public string FilePath
{
get
{
return (string) ViewState["FilePath"];
}
set
{
ViewState["FilePath"] = value;
}
}
YOU SHOULD DO IT IN THIS WAY.
if (imgUpload.HasFile)
{
String strFileName = imgUpload.PostedFile.FileName;
imgUpload.PostedFile.SaveAs(Server.MapPath("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
SqlCommand cmd01 = new SqlCommand("insert into img (FeaturedImg) Values (#img)", cn01);
cmd01.Parameters.AddWithValue("#img", ("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
}
With this code you can upload file in a particular location in your sites root directory.
and the path will be stored in database as string.
so you can access the file just by using the path stored in database.
If you cant understand anything. or wanna know more u can contact me or ask me here in comments.
I need to save a file as .csv in client machine. I am using the code below.
protected void btnGen_Click(object sender, EventArgs e)
{
try
{
string fileName = "test";
string attachment = "attachment; filename=" + fileName + ".csv";
List<string> lst1 = new List<string> { "wert", "fds", "hjgfh", "hgfhg" };
List<string> lst2 = new List<string> { "hgfds", "hdfg", "yretg", "treter" };
List<string> lst3 = new List<string> { "hgfdgf", "gfdg", "gfdgf", "ghfdg" };
List<List<string>> lst = new List<List<string>> { lst1, lst2, lst3 };
StringBuilder sb = new ExportFacade().GenerateStringBuilder(lst);
Response.ContentType = "text/csv" ;
lblProgress.ForeColor = System.Drawing.Color.Green;
lblProgress.Text = "File created and write successfully!";
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
Response.Write(sb.ToString());
lblProgress.ForeColor = System.Drawing.Color.Green;
lblProgress.Text = "File created and write successfully!";
Response.Flush();
Response.End();
}
catch (Exception ex)
{
lblProgress.ForeColor = System.Drawing.Color.Red;
lblProgress.Text = "File Saving Failed!";
}
}
I am not using update panels.
When I click on the button I get the following error
Sys.WebForms.PageRequestManagerParserErrorException: The message
received from the server could not be parsed. Common causes for this
error are when the response is modified by calls to Response.Write(),
response filters, HttpModules, or server trace is enabled.
It will be a great help to me if you can help me to get rid of this problem.
thank you.
I solved it. Ajax script manager in the master page has created the problem. After removing it, the function worked properly. But labels are not being updated as response is not for the page.
How can i write a datatable content on web page in XMl foramte in asp.net?
i also need to customize the datatable before writing to web page.
Edited:-
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/xml";
DataTable dt = new DataTable("XML");
String email = EmailAddress.Text.ToString();
dt.Load(obj.GetXML("XYZ#gmail.com"));
//now i want this dt to dosplayed in the XMl form on the same page, how can i achieve this?
'XmlDocument xml = new XmlDocument();
'XmlTextReader xr=new XmlTextReader(
'WriteGoogleMap(dt.ToString(), Response.OutputStream);
'Response.End();
//System.Xml.
}
Try this :
public string GetXml(string urlBase)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
StringBuilder output = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
// Repeat this code:
writer.WriteStartElement("url");
writer.WriteElementString("loc", "[your url]");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
return output.ToString();
}
Then use the result to feed a label :
<script runat="server" type=text/C#>
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = HttpUtility.HtmlEncode(
GetXml("http://www.dotnetperls.com/")
);
}
</script>
[Edit]
I think you should start by the beginning. Do not mix all concepts in your single question. Spend time for learning the basics (read books, take courses, etc.). In your specific case, I suggest you to split the work in several layers:
A data layer the is responsible to build a datatable
A business or service layer, capable of creating the xml document from the databable
A presentation layer that will contains :
a custom http handler (.ashx) that will return the xml
a visual page that can show the html representation of the Xml
good luck
DataTable has method named:
WriteXml
SENARIO: i have few folders on my FTP server, belongs to particular user. Suppose i have 10GB total space and i assign 1GB to each user i.e can accomodate 10 users having 1GB each.
now users can add/delete/edit any type of file to utilize the storage space. All i need to do is to restrict users not to exceed 1gb space for their file storage. For this i want to use FileSystemWatcher to notify me that a user had created/deleted/edited a file so that i can minimize the space from 1gb incase of creation of a file or add a space incase of deletion.
this is the piece of coding using FSW. when user gets loged-in with proper id and password, respective folder is opened (present at FTP server) where he can add/delete/edit any type of file and according to that i hav to monitor d space ulitilized by him.
but d problem is the event handlers (written in console). i dont understand what happens when this code is being runned... i dontknow how to use FSW class so that i can monitor d changes user is making in his folder.
please help ... THANX
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class _Default: System.Web.UI.Page {
public class ClsFileSystemWatcher {
public static void OnChanged(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnDeleted(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnCreated(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnRenamed(object source, RenamedEventArgs e) {
Console.WriteLine("File "+e.OldFullPath+" [Changed to] "+e.FullPath);
}
public static void OnError(object source, ErrorEventArgs e) {
Console.WriteLine("Error "+e);
}
public void FileWatcher(string InputDir) {
using (FileSystemWatcher fsw = new FileSystemWatcher()) {
fsw.Path = InputDir;
fsw.Filter = #"*";
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName|NotifyFilters.Attributes|NotifyFilters.LastAccess|NotifyFilters.LastWrite|NotifyFilters.Security|NotifyFilters.Size|NotifyFilters.CreationTime|NotifyFilters.DirectoryName;
fsw.Changed += OnChanged;
fsw.Created += OnCreated;
fsw.Deleted += OnDeleted;
fsw.Renamed += OnRenamed;
fsw.Error += OnError;
fsw.EnableRaisingEvents = true;
//string strOldFile = InputDir + "OldFile.txt";
//string strNewFile = InputDir + "CreatedFile.txt";
//// Making changes in existing file
//using (FileStream stream = File.Open(strOldFile, FileMode.Append))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Appending new line in Old File");
// sw.Flush();
// sw.Close();
//}
//// Writing new file on FileSystem
//using (FileStream stream = File.Create(strNewFile))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Writing First line into the File");
// sw.Flush();
// sw.Close();
//}
//File.Delete(strOldFile);
//File.Delete(strNewFile);
// Minimum time given to event handler to track new events raised by the filesystem.
Thread.Sleep(1000);
}
}
}
private DAL conn;
private string connection;
private string id = string.Empty;
protected void Page_Load(object sender, EventArgs e) {
connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\project\\Desktop\\BE prj\\dbsan.mdb;Persist Security Info=False";
conn = new DAL(connection);
////*** Opening Respective Folder of a User ***////
DirectoryInfo directories = new DirectoryInfo(#"C:\\Inetpub\\ftproot\\san\\");
DirectoryInfo[] folderList = directories.GetDirectories();
if (Request.QueryString["id"] != null) {
id = Request.QueryString["id"];
}
string path = Path.Combine(#"C:\\Inetpub\\ftproot\\san\\", id);
int folder_count = folderList.Length;
for (int j = 0; j < folder_count; j++) {
if (Convert.ToString(folderList[j]) == id) {
Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
}
}
ClsFileSystemWatcher FSysWatcher = new ClsFileSystemWatcher();
FSysWatcher.FileWatcher(path);
}
}
Each time you reload the page you create new FSW - in that case you won't get any events raised, because from the point of newly created FSW nothing was changes. Try to preserve your FileSystemWatcher object in the Session state.
So flow would look like:
User logs in – you create FSW and preserve it in Session
User reloads the page – get FSW from Session (do not create new one)
You should create a worker role (service) for this type of thing. I think it is not appropriate to have something like this inside of a page.