This is a code that I wrote for my open button ... but I have error on "DisplayErrorMessage" part.
What should I write instead? or how can I define it in order not to have the error again.
protected void btnOpen_Click(object sender, EventArgs e)
{
txtFileName.Text = txtFileName.Text.Trim();
if (txtFileName.Text == string.Empty)
{
string strErrorMessage = "you did Not specify file for opening!";
DisplayErrorMessage(strErrorMessage);
}
string strFileName = txtFileName.Text;
string strRootRelativePath = "~/app_data/pageContent";
string strRootRelativePathName =
string.Format("{0}/{1}", strRootRelativePath, strFileName);
string strPathName = Server.MapPath(strRootRelativePathName);
System.IO.StreamReader ostreamReader = null;
try
{
ostreamReader = new System.IO.StreamReader(strPathName, System.Text.Encoding.UTF8);
litPageMessages.Text = ostreamReader.ReadToEnd();
}
catch (Exception ex)
{
litPageMessages.Text = ex.Message;
}
finally
{
if (ostreamReader != null)
{
ostreamReader.Dispose();
ostreamReader= null;
}
}
}
If you want to alert your error message in the browser, you could do the following.
Add a class file in your App_Code folder, say Helpers.cs
Then, open it and add the following code:
public class Helpers
{
public static void DisplayErrorMessage(Page page, string msg)
{
string script = "<script>alert('" + msg + "');</script>";
if (!page.ClientScript.IsStartupScriptRegistered("MyAlertMsgHandler"))
page.ClientScript.RegisterStartupScript(page.GetType(), "MyAlertMsgHandler", script);
}
}
Lately, call this method from your code behind like this:
Helpers.DisplayErrorMessage(this.Page, "Error message details.");
Either create a function which takes message in the parameter and use MessageBox.Show() method to Display the error message.
or
Just Call MessageBox.Show( this, strErrorMessage ) instead of DisplayErrorMessage(strErrorMessage);
Try This...
void DisplayErrorMessage(string msg)
{
string script = "<script>alert('" + msg + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
Related
I have added a CEF control into a WinForm. And I have added an invokeCapture method that is expected to capture the screen shot of the entire page of the CEF. It works fine when first invoking. But errors are encountered since second invoking and more, which the message is "Generated MessageID 100002 doesn't match returned Message Id 100001". How can I capture screen shot more than once?
I have copied the screenshot function code from https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Example/DevTools/DevToolsExtensions.cs to my project and renamed the namespace of it to winformcefdemo.CefSharp.Example.
The variable lastMessageId of the class DevToolsClient, in which class CaptureScreenshot executes ExecuteDevToolsMethodAsync in order to run command "Page.CaptureScreenshot", is private and there are either no getter nor setter to it. It seems to be annoying. The method ExecuteDevToolsMethodAsync would want to compare the message ID of what the method ExecuteDevToolsMethod returns to the automatically increased message ID of the DevToolsClient itself. The DevtoolsClient in the method CaptureScreenShotAsPng is what browser.GetDevToolsClient() returns (in the line 36 of the link above). And I have also checked the implementation of the method GetDevToolsClient. It is also using DevToolsClient devToolsClient = new DevToolsClient(browser); in CefSharp.DevToolsExtensions.
private async void invokeCapture()
{
try
{
byte[] result = await winformcefdemo.CefSharp.Example.DevTools.DevToolsExtensions.CaptureScreenShotAsPng(browser);
// task.Start();
// byte[] result = task.Result;
SaveFileDialog dialog = new SaveFileDialog();
DialogResult dresult = dialog.ShowDialog();
if (dresult == DialogResult.OK)
{
string path = dialog.FileName;
try
{
File.WriteAllBytes(path, result);
MessageBox.Show(path + " saved success");
} catch (Exception e)
{
MessageBox.Show(path + "Unknown error occurred when saving to file: " + e.Message);
}
}
}
catch (Exception ee)
{
MessageBox.Show("Unknown error occurred when capturing: " + ee.Message);
}
}
Solved in Chinese community of CSDN
Use no DevToolsExtensions. Use PageClient Instead. DevToolsExtensions does have issues that are not solved.
And PageClient should be defined globally. Do not define it in the method.
# Source: https://bbs.csdn.net/topics/398544662
CefSharp.DevTools.Page.PageClient pageClien= null;
private async void invokeCapture()
{
if(pageClien==null)
{
pageClien = webBrowser.GetBrowser().GetDevToolsClient().Page;
}
var result = await pageClien.CaptureScreenshotAsync();
if (result.Data != null)
{
MemoryStream ms = new MemoryStream(result.Data);
ms.Write(result.Data, 0, result.Data.Length);
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "PNG Picture (*.PNG)|*.PNG";
DialogResult dresult = dialog.ShowDialog();
if (dresult == DialogResult.OK)
{
string path = dialog.FileName;
try
{
File.WriteAllBytes(path, result);
MessageBox.Show(path + " saved success");
} catch (Exception e)
{
MessageBox.Show(path + "Unknown error occurred when saving to file: " + e.Message);
}
}
}
}
In my program I am loading a text files information into a rich text box. When the user clicks the clear button I want the files contents to be empty and display it again on the rich text box. However when I try to clear an error pops up that the file is already in use.
I am not sure of of what is going on with this, I have a suspicion it has to do with closing the stream reader or creating a new one. Either way I am not quite sure.
Does anyone have any thoughts of what is going on with this?
Code:
namespace FileLocationAutomation
{
public partial class ViewLog : Form
{
public ViewLog()
{
InitializeComponent();
}
#region Variables
string str = "";
#endregion
#region Ok Button
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region Form Load
private void ViewLog_Load(object sender, EventArgs e)
{
//catch any exception
try
{
//load the log thats kept on the users machine into the rich text object
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Clear Log
//clear the log file and display it on the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
}
}
The problem is that you try to write to the file to clear it while still holding it open. The simplest change is to move the call to File.WriteAllText(GlobalVars.strLogPath, String.Empty); to after where you close the file, as follows:
#region Clear Log
//clear the log file and display it on the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
A better change would probably to use the static read method, since you're reading the whole file in one go there's no need to use the StreamReader.
private void btnClear_Click(object sender, EventArgs e)
{
try
{
rtxtView.Text = File.ReadAllText(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The problem is strictly here:
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
Make it look like this:
try
{
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
Or since reading a blank file back is useless, do it like this:
try
{
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
rtxtView.Text = String.Empty;
}
enclose the StreamReader declaration in using block {}to make sure that it gets disposed.
Try This:
using(StreamReader read = new StreamReader(GlobalVars.strLogPath))
{
str = read.ReadToEnd();
rtxtView.Text = str;
}
OR
rtxtView.Text = File.ReadAllText(GlobalVars.strLogPath);
You may change the order.
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
// close the stream first.
read.Close();
rtxtView.Text = str;
}
I want to create a C# application using windows forms that let me upload files to a webserver, i have seen a lot of tutorial and everyone of them prove to be useless to solve my problem.
and with my project i have the next code in the button for upload
WebClient client = new WebClient();
client.UploadFile("http://localhost:8080/", location);
from here i had have several errors, an try multiple ideas, some of my more common errors are 404 not found or innaccessible path, also sometimes it doenst display me an error and works but the file doesn't save in the indicated path.
some of the links i use to solve the problem are the next ones:
http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx
http://www.c-sharpcorner.com/Blogs/8180/
How to upload a file in window forms?
upload a file to FTP server using C# from our local hard disk.
private void UploadFileToFTP()
{
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential("user", "pass");
byte[] b = File.ReadAllBytes(#"E:\sample.txt");
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
if(ftpResp.StatusDescription.StartsWith("226"))
{
Console.WriteLine("File Uploaded.");
}
}
}
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("http://www.yoursite.com/UploadMethod/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadMethod()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
winform
string fullUploadFilePath = #"C:\Users\cc\Desktop\files\test.txt";
string uploadWebUrl = "http://localhost:8080/upload.aspx";
client.UploadFile(uploadWebUrl , fullUploadFilePath );
asp.net create upload.aspx as below
<%# Import Namespace="System"%>
<%# Import Namespace="System.IO"%>
<%# Import Namespace="System.Net"%>
<%# Import NameSpace="System.Web"%>
<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {
foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
}
}
</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
you should set in win app
WebClient myWebClient = new WebClient();
string fileName = "File Address";
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);
// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);
then set read and write permission for SubDir
create a simple API Controller file in the Controllers folder and name it UploadController.
Let’s modify that file by adding a new action that will be responsible for the upload logic:
[HttpPost, DisableRequestSizeLimit]
public IActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _host.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
string ext = Path.GetExtension(file.FileName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = "";
string name = Path.GetFileNameWithoutExtension(file.FileName);
string fullPath = Path.Combine(newPath, name + ext);
int counter = 2;
while (System.IO.File.Exists(fullPath))
{
fileName = name + "(" + counter + ")" + ext;
fullPath = Path.Combine(newPath, fileName);
counter++;
}
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok();
}
return Ok();
}
catch (System.Exception ex)
{
return BadRequest();
}
}
We are using a POST action for the upload-related logic and disabling the request size limit as well.
and use code below in Winform
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://localhost/api/upload");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
client.UploadFileAsync(uri, directoryfile);
client.UploadFileCompleted += Client_UploadFileCompleted;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show("done");
}
Goodluck
I am having trouble calling the string "rlist" from:
public void main()
{
string rlist;
if (radioButton1.Checked)
textBox1.Enabled = false;
textBox1.ReadOnly = true;
rlist = "text";
}
to
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "WTF Files (*.wtf)|*.wtf";
openFile.Title = "Please Pick your realmlist file:";
if (openFile.ShowDialog() == DialogResult.Cancel)
return;
try
{
textBox5.Text = openFile.FileName;
string file = openFile.FileName;
TextWriter rlist_writer = new StreamWriter (openFile.FileName);
rlist_writer.WriteLine(rlist);
rlist_writer.Close();
}
catch (Exception)
{
MessageBox.Show("Error opening file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
I get the error on this line:
rlist_writer.WriteLine(rlist);
is it possible to call a string from one function and send it to the other with the same value it had in the function it was originally pulled from?
By the sounds of your question,
Your string is local to your main function.
So judging by your method names and knowledge of winforms(presumed again)
you need to make your string class level
string rlist;
public void main()
{
rlist = "yay"
public void button1_Click(object sender, EventArgs e)
{
someText = rlist;
As it currently stands you are not able to, as temporary (local) variables will be cleaned through garbage collection when you leave the method
Edit
You may wish to review this also
try
{
textBox5.Text = openFile.FileName;
using(TextWriter rlist_writer = new StreamWriter (openFile.FileName))
{
rlist_writer.WriteLine(rlist);
}
}
You can define that variable in your class scope, then if you call that variable in your button_click event, it will maintain the same value as in your main method.
I want to put a test loop on the button click event. When I click this button, it reads the contents of the text file, but I want it to pop up an error message showing “unable to read file”, if it’s not a text file....
This is my code
private void button3_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
How can I go about it?
A few if-statements and the namespace System.IO will do it
string filename = textBox1.Text;
if (Path.GetExtension(filename).ToLower()) == ".txt") {
if (File.Exists(filename)) {
// Process the file here
} else {
MessageBox.Show("The file does not exist");
}
} else {
MessageBox.Show("Not a text file");
}
Not the best code, but it should work. Ideally you would separate the logic into two methods, a function to check the file exists and is a text file (returning a bool), another to read the contents if the check function returned true and populate the textbox with the contents.
EDIT: This is better:
private void button3_Click(object sender, EventArgs e)
{
string filePath = textBox1.Text;
bool FileValid = ValidateFile(filePath);
if (!IsFileValid)
{
MessageBox.Show(string.Format("File {0} does not exist or is not a text file", filePath));
}
else
{
textbox2.Text = GetFileContents(filePath);
}
}
private bool IsFileValid(string filePath)
{
bool IsValid = true;
if (!File.Exists(filePath))
{
IsValid = false;
}
else if (Path.GetExtension(filePath).ToLower() != ".txt")
{
IsValid = false;
}
return IsValid;
}
private string GetFileContents(string filePath)
{
string fileContent = string.Empty;
using (StreamReader reader = new StreamReader(filePath))
{
fileContent = reader.ReadToEnd();
}
return fileContent;
}