I want to write some result to the console in ASP.NET (C#).
It works in a Window application, but a Web application does not work.
Here is what I have tried:
protected void btonClick_Click(object sender, EventArgs e)
{
Console.WriteLine("You click me ...................");
System.Diagnostics.Debug.WriteLine("You click me ..................");
System.Diagnostics.Trace.WriteLine("You click me ..................");
}
But I see nothing in the Output panel. How do I solve this problem?
Console.Write will not work in ASP.NET as it is called using the browser. Use Response.Write instead.
See Stack Overflow question Where does Console.WriteLine go in ASP.NET?.
If you want to write something to Output window during debugging, you can use
System.Diagnostics.Debug.WriteLine("SomeText");
but this will work only during debug.
See Stack Overflow question Debug.WriteLine not working.
using System.Diagnostics;
The following will print to your output as long as the dropdown is set to 'Debug' as shown below.
Debug.WriteLine("Hello, world!");
If for whatever reason you'd like to catch the output of Console.WriteLine, you CAN do this:
protected void Application_Start(object sender, EventArgs e)
{
var writer = new LogWriter();
Console.SetOut(writer);
}
public class LogWriter : TextWriter
{
public override void WriteLine(string value)
{
//do whatever with value
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.
You shouldn't launch as an IIS server. check your launch setting, make sure it switched to your project name( change this name in your launchSettings.json file ), not the IIS.
Use response.write method in the code-behind.
Make sure you start your application in Debug mode (F5), not without debugging (Ctrl+F5) and then select "Show output from: Debug" in the Output panel in Visual Studio.
Related
When a user runs the program for the first time I want a message box to show up.
I was thinking of something like this:
private void Form1_Load(object sender, EventArgs e)
{
if(firstTime)
{
MessageBox.Show("Welcome");
}
How could I get my program to display a message box when a user launches the program for the first time in c#?
You would need to store that information somewhere
File
System registry
Database
Settings in application
Then read the value, and setup the firstTime flag prior to check.
You can add a parameter to the application settings.
Go to the solution explorer in the section Properties and double click on Settings.settings.
Add a parameter named for example IsFirstLaunch and set type to bool with value True.
Then you can write:
if ( Properties.Settings.Default.IsFirstLaunch )
{
Properties.Settings.Default.IsFirstLaunch = false;
Properties.Settings.Default.Save();
MessageBox.Show("Welcome");
}
The settings are stored in:
c:\Users\{UserName}\AppData\Local\{Assembly CompanyName}\{Assembly Name}.Url__________
So be careful to set Assembly CompanyName in the AssemblyInfo.cs in the same section.
Assembly Name is from the application project properties (double click on this Properties section).
You can delete this file to test again.
I use an IAutoTamper2 to colorcode relevant requests/responses to my application based on url and other information.
This is very helpful for debugging. However when someone sends me a saved .saz file, I no longer see my helpful colorcodes. How can I apply the IAutoTamper2 logic when a file is imported.
I looked at the ISessionImporter interface but you have to start from scratch. Is there a way to inherit from the default importer and add my logic that occurs in the IAutoTamper2?
I've looked at all the documentation about extensions on the telerik website but couldn't find anything relevant. Any ideas?
I figured out how to do it. There is a OnLoadSAZ event that I can use to change loaded sessions.
This is my code:
public void OnLoad()
{
FiddlerApplication.OnLoadSAZ += HandleLoadSaz;
}
private void HandleLoadSaz(object sender, FiddlerApplication.ReadSAZEventArgs e)
{
FiddlerApplication.UI.lvSessions.BeginUpdate();
foreach (var session in e.arrSessions)
{
OnPeekAtResponseHeaders(session); //Run whatever function you use in IAutoTamper
session.RefreshUI();
}
FiddlerApplication.UI.lvSessions.EndUpdate();
}
I hope that helps someone else.
Hello guys I'm new to the forum also programming and need some help about a project.
So I recently start developing a program that firstly must add its path at the end of Registry => Environment => Path.
For this job I created project (MainLogic) which contain a class (Program) that do the job, Installer Class that contains this events below and configured Setup Project. SOURCE
public InstallerClass1()
{
this.Committed += InstallerClass1_Committed;
this.Committing += InstallerClass1_Committing;
}
private void InstallerClass1_Committing(object sender, InstallEventArgs e)
{
//Console.WriteLine("");
//Console.WriteLine("Committing Event occurred.");
//Console.WriteLine("");
}
private void InstallerClass1_Committed(object sender, InstallEventArgs e)
{
Directory.SetCurrentDirectory(Path.GetDirectoryName
(Assembly.GetExecutingAssembly().Location));
Process.Start(Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location) + "\\MainLogic.exe");
}
The program was installed correctly but MainLogic.exe file I call after installation cause an error and can't start. The exception is Null Reference at MainLogic.Program.Main(String[] args)
Here is a picture for better understanding -
Is there a way to avoid that exception or could you offer me another that will work.
*** Here what i found. I can execute creating and typing in to file. Writing on the console. Probably a lot of other stuff without problem. But when try to execute this peace of code which actually I have to use...
Registry.CurrentUser.OpenSubKey("Pass Key", RegistryKeyPermissionCheck.ReadWriteSubTree).SetValue("Finaly", "Done");
Registry.CurrentUser.Close();
...the exception I described above occurs. Suggestions?
So the main reason for all those "exercises" is because I want to implement ffmpeg in my application.
I guess you are hear about ffmpeg (a video/audio processing program that works in command prompt).
So what I'm working on is to implement it in my project for mp3 extracting from video files but I wanna make it more user friendly so the user can pass commands through GUI and from there my code should do the other job. So ffmpeg works through command prompt (I know there is a wrappers but I'm not very satisfied with what read about) but firstly you have to add his path to Path's value in the registry. And here's where my problem came from.
Maybe it's sounds stupid for you but you know.. when you start something make it all the way.
If course you can just add exception handling and see what goes wrong but you don`t neet that anyway. Try to set the registry key directly in your Installer
[RunInstaller(true)]
public partial class Installer1 : Installer
{
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
const string key_path = "SOFTWARE\\YourCompany\\YourApplication";
const string key_value_name = "InstallationDirectory";
RegistryKey key = Registry.LocalMachine.OpenSubKey(key_path, Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
if (key == null)
{
key = Registry.LocalMachine.CreateSubKey(key_path);
}
string tgt_dir = "someDirectory";
key.SetValue(key_value_name, tgt_dir);
}
if you want to alter the path enironment variables set the key there. You can simply add a new variable or look for an exiting one (including the value) for example with Registry.GetValue MSDN-Link
User Variables
HKEY_CURRENT_USER\Environment
System Variables
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
I have to pretty simple pieces of code:
private void frmMain_Load(object sender, EventArgs e)
{
string[] EmployeeNames = Settings.Default.Employee_Names.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
employee_NameComboBox.Items.AddRange(EmployeeNames);
}
And
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
string Employee_Names = string.Empty;
foreach (string Name in employee_NameComboBox.Items)
{
Employee_Names += Name + ";";
}
if (Employee_Names.Length > 1)
{
Settings.Default.Employee_Names = Employee_Names.Substring(0, Employee_Names.Length - 1);
Settings.Default.Save();
}
}
So, to test my code I added the values "Foo;Bar"
To my Settings.Settings in the VS Designer
but when I run the Code Nothing comes up. So I add this code:
private void AddName()
{
if (!employee_NameComboBox.Items.Contains(employee_NameComboBox.Text))
{
employee_NameComboBox.Items.Add(employee_NameComboBox.Text);
}
}
And then I call it on the Leave event of employee_NameComboBox:
private void employee_NameComboBox_Leave(object sender, EventArgs e)
{
AddName();
}
To test this I enter the employee_NameComboBox and type in "Employee1" and leave the CB then enter again and type in "Employee2" and Leave now when I click on the drop down I have these strings in the Items Collection. Great!
But when I close the application and then goto my settings.settings under properties in the Solution Explorer the values "Foo;Bar" are still there.
Continue to start Debugging again and when I click the drop down, the values are "Employee1" and "Employee2". In turn I search through the Solutions Directory in Windows Explorer to try and find the new settings file and I simply CAN NOT find ANY files with "Employee1" or "Employee2" all I see in ANY files is "Foo;Bar".
How can this be? I am saving to somewhere but where!
Also Why doesn't the debugger use the values in the settings.settings or App.Config files?!?!?!
Note: I also tried doing a Find from Visual Studios and Searched Entire Solution for the value Employee1 to no avail.
My end result is that I would like to send out an application with editable combobox that can be saved and edited without a Re-compile.
When such setting are changed at run-time, the values are stored in the following directory:
C:\Documents and Settings\<username>\Local Settings\Application Data
That's where the app then goes and looks for them the next time.
The settings are overwritten on each build by whatever you have set up in VS. If you want to use the settings from a previous compilation (or once deployed to a client machine, a previous version after an update) you have to use Settings.Upgrade(). This should be called once per runtime, most easily in the constructor. See this other StackOverflow question. C# .NET Application Settings and Upgrading
I would like to print some traces during the requests processing.
But when I make Console.WriteLine("something") in this environment, nothing is shown.
What is missing, what do I need to do in order to use console to print these traces?
Use Debug.Write() and and watch the results come out through the debugger output window in the IDE.
Alternatively, use the ASP.NET trace feature, which is quite powerful. Once you have enabled tracing, you can navigate to the trace.axd page in your web app's root directory. This page will show the trace messages for your app.
In addition to the methods already mentioned you can simply write to a log file:
File.AppendAllText(#"c:\log.txt", #"Debug Message Here!" + Environment.NewLine);
Of course you could use Server.MapPath to write the file in your web directory.
I know this is late, but you can write to your Javascript console from your C# script using the following class
public static class Javascript
{
static string scriptTag = "<script type=\"\" language=\"\">{0}</script>";
public static void ConsoleLog(string message)
{
string function = "console.log('{0}');";
string log = string.Format(GenerateCodeFromFunction(function), message);
HttpContext.Current.Response.Write(log);
}
public static void Alert(string message)
{
string function = "alert('{0}');";
string log = string.Format(GenerateCodeFromFunction(function), message);
HttpContext.Current.Response.Write(log);
}
static string GenerateCodeFromFunction(string function)
{
return string.Format(scriptTag, function);
}
}
That way you can see your log messages in real time as you click through the site, just as you would in js.
You can use Response.Write to write output to your page for debugging, or use alert in javascript, or even write to a log file. There are many ways to get debugging output. There's also a log4net for .Net that you can use (similar to log4j)
Given that it's an ASP.NET application, I would do:
Page.Trace.Write ("Something here");
Then enable trace either for the page or the application and then just go to ~/Trace.axd to see the results (they can also be at the end of the page output, depending on the configuration option that you choose).
Where are you looking for the output?
Console.WriteLine() writes to the command line - not to the webpage. Either use Response.Write() to write onto the webpage or start up your application in the Visual Studio debugger to look at the command line output.