Manual Elmah Logging dosnt work properly in MVC - asp.net-mvc

I used ELAMH 1.2 to log errors in MVC 5. It work well for 404 500... HTTP errors and in controller's catch blocks.
public ActionResult Index()
{
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("test"));
try
{
var a = 0;
var b = 1 / a;
}
catch(Exception e)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
}
return View();
}
i get two log for this code.
but it dosent work in a static class like below. i dont get any exception while running ErrorSignal.FromCurrentContext().Raise(e);.
public static class FileUtility
{
public static string SaveSampleFile(HttpPostedFileBase file)
{
try
{
var b = 0;
var a = 1/b;
}
catch (Exception e)
{
ErrorSignal.FromCurrentContext().Raise(e);
return null;
}
}
}
no error log nothing happen!

I have also seen this problem when calling ELMAH logger without any HttpContext in class library projects.
I used the old manual way to get around this:
Elmah.ErrorLog.GetDefault(null).Log(new Error(ex));

Related

System.Exception, xUnit calling HttpDelete action on the controller

I'm getting "System.Exception : Exception of type 'System.Exception' was thrown." when I'm calling:
var result = controllerApi.DeleteCliente(2);
the DeleteCliente code (inside the controller):
[Authorize(Roles = "PaginaDeClientes")]
[HttpDelete]
public IActionResult DeleteCliente(int clienteId)
{
var cliente = _context.Clientes.Find(clienteId);
if (cliente == null) { return NotFound(); }
_context.Clientes.Remove(cliente);
var result = _context.SaveChanges();
if (result <= 0)
{
throw new Exception();
}
return Ok();
}
My test DeleteCliente():
[Fact]
public void DeleteCliente()
{
var controllerApi = new PoollGest.Controllers.Api.ClientesController(_context);
_context.Clientes.Add(new Cliente()
{
ClienteId = 2,
Nome = "Jose",
Desconto = 20,
});
var result = controllerApi.DeleteCliente(2);
Assert.IsType<OkResult>(result);
}
This controller currently only has the deleteCliente action, for reference I have run other tests where I create an object in my context and run one of the "crud" action's and I had no problems, not sure what I'm doing wrong here
Error:
I couldn't find the exact cause of the problem when I run the debug with the breakpoints, but it works now.
I Basically rebuild the entire project, deleted the migrations, build the bd again. And it works now, so if you have a similar problem I recommend you to rebuild your project.

Umbraco unpublish Event not working for the current node

I am developing Umbraco 7 MVC application and my requirement is to add Item inside Umbraco. Item name should be unique. For that used the below code but I am getting the error "Oops: this document is published but is not in the cache (internal error)"
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
if(newsItemExists)
{
e.Cancel = true;
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
Then I tried adding code to unpublish but its not working i.e the node is getting published. Below is my code
private void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
try
{
int itemId=1234; //CurrentPublishedNodeId
if(newsItemExists)
{
IContent content = ContentService.GetById(itemId);
ContentService.UnPublish(content);
library.UpdateDocumentCache(item.Id);
}
}
catch (Exception ex)
{
e.Cancel = true;
Logger.Error(ex.ToString());
}
}
But with the above code, if you give the CurrentPublishedNodeId=2345 //someOthernodeId its unpublished correctly.
Can you please help me on this issue.
You don't have to do this, Umbraco will automatically append (1) to the name if the item already exists (so it IS unique).
If you don't want this behavior you can check in the following way:
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentService.Publishing += ContentService_Publishing;
}
private void ContentService_Publishing(Umbraco.Core.Publishing.IPublishingStrategy sender, PublishEventArgs<IContent> e)
{
var contentService = UmbracoContext.Current.Application.Services.ContentService;
// It's posible to batch publish items, so go through all items
// even though there might only be one in the list of PublishedEntities
foreach (var item in e.PublishedEntities)
{
var currentPage = contentService.GetById(item.Id);
// Go to the current page's parent and loop through all of it's children
// That way you can determine if any page that is on the same level as the
// page you're trying to publish has the same name
foreach (var contentItem in currentPage.Parent().Children())
{
if (string.Equals(contentItem.Name.Trim(), currentPage.Name.Trim(), StringComparison.InvariantCultureIgnoreCase))
e.Cancel = true;
}
}
}
I think your problem might be that you're not looping through all PublishedEntities but using some other way to determine the current page Id.
Note: Please please please do not use the library.UpdateDocumentCache this, there's absolutely no need, ContentService.UnPublish will take care of the cache state.

About good practice for GLib.Application and Soup.Server

I'm trying to create a simple server in vala using libsoup.
I am wondering if it is a good way to start a Soup.Server from a GLib.Application. Since using it synchronously (run is deprecated) is not recommended, the only way I found to keep it alive is to hold the default application.
public class Simple.Server : Soup.Server
{
public Server () {
Application.get_default ().hold ();
add_handler(null, null_handler);
}
private void null_handler (Soup.Server server, Soup.Message message,
string path, HashTable<string,string>? query,
Soup.ClientContext client) {
GLib.message ("path: %s", path);
message.status_code = 404;
message.set_response ("text/plain", Soup.MemoryUse.COPY, "".data);
}
}
public class Simple.App : Application
{
private Simple.Server server;
App () {
Object (application_id: "org.dev.simple-server",
flags: ApplicationFlags.FLAGS_NONE);
}
protected override void activate () {
base.activate ();
server = new Simple.Server();
try {
server.listen_all(8080, 0);
}
catch (Error e) {
GLib.message ("Error n°%u: %s", e.code, e.message);
}
}
protected override void shutdown () {
base.shutdown ();
server.disconnect ();
}
static int main (string[] args) {
App app = new Simple.App();
return app.run (args);
}
}
This is mimic of my code.
So here is the question, is it a good practice for starting the server, still using GLib.Application, or should I use (like examples say) only the server, starting/stopping manually the MainLoop ?
thanks.

Continuously output from StandardOutput to text box in Visual C# [duplicate]

I have an external dll written in C# and I studied from the assemblies documentation that it writes its debug messages to the Console using Console.WriteLine.
this DLL writes to console during my interaction with the UI of the Application, so i don't make DLL calls directly, but i would capture all console output , so i think i got to intialize in form load , then get that captured text later.
I would like to redirect all the output to a string variable.
I tried Console.SetOut, but its use to redirect to string is not easy.
As it seems like you want to catch the Console output in realtime, I figured out that you might create your own TextWriter implementation that fires an event whenever a Write or WriteLine happens on the Console.
The writer looks like this:
public class ConsoleWriterEventArgs : EventArgs
{
public string Value { get; private set; }
public ConsoleWriterEventArgs(string value)
{
Value = value;
}
}
public class ConsoleWriter : TextWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
public override void Write(string value)
{
if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value));
base.Write(value);
}
public override void WriteLine(string value)
{
if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value));
base.WriteLine(value);
}
public event EventHandler<ConsoleWriterEventArgs> WriteEvent;
public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent;
}
If it's a WinForm app, you can setup the writer and consume its events in the Program.cs like this:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
using (var consoleWriter = new ConsoleWriter())
{
consoleWriter.WriteEvent += consoleWriter_WriteEvent;
consoleWriter.WriteLineEvent += consoleWriter_WriteLineEvent;
Console.SetOut(consoleWriter);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
static void consoleWriter_WriteLineEvent(object sender, Program.ConsoleWriterEventArgs e)
{
MessageBox.Show(e.Value, "WriteLine");
}
static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e)
{
MessageBox.Show(e.Value, "Write");
}
It basically amounts to the following:
var originalConsoleOut = Console.Out; // preserve the original stream
using(var writer = new StringWriter())
{
Console.SetOut(writer);
Console.WriteLine("some stuff"); // or make your DLL calls :)
writer.Flush(); // when you're done, make sure everything is written out
var myString = writer.GetStringBuilder().ToString();
}
Console.SetOut(originalConsoleOut); // restore Console.Out
So in your case you'd set this up before making calls to your third-party DLL.
You can also call SetOut with Console.OpenStandardOutput, this will restore the original output stream:
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
Or you can wrap it up in a helper method that takes some code as an argument run it and returns the string that was printed. Notice how we gracefully handle exceptions.
public string RunCodeReturnConsoleOut(Action code)
{
string result;
var originalConsoleOut = Console.Out;
try
{
using (var writer = new StringWriter())
{
Console.SetOut(writer);
code();
writer.Flush();
result = writer.GetStringBuilder().ToString();
}
return result;
}
finally
{
Console.SetOut(originalConsoleOut);
}
}
Using solutions proposed by #Adam Lear and #Carlo V. Dango I created a helper class:
public sealed class RedirectConsole : IDisposable
{
private readonly Action<string> logFunction;
private readonly TextWriter oldOut = Console.Out;
private readonly StringWriter sw = new StringWriter();
public RedirectConsole(Action<string> logFunction)
{
this.logFunction = logFunction;
Console.SetOut(sw);
}
public void Dispose()
{
Console.SetOut(oldOut);
sw.Flush();
logFunction(sw.ToString());
sw.Dispose();
}
}
which can be used in the following way:
public static void MyWrite(string str)
{
// print console output to Log/Socket/File
}
public static void Main()
{
using(var r = new RedirectConsole(MyWrite)) {
Console.WriteLine("Message 1");
Console.WriteLine("Message 2");
}
// After the using section is finished,
// MyWrite will be called once with a string containing all messages,
// which has been written during the using section,
// separated by new line characters
}

previous instance still active error in blackberry

I created app which user can start from menu and from icon. I do not use GlobalEventListener in my app, just register ApplicationMenuitem. And now I am getting error: previous instance still active when launch my app.
Steps to reproduce not so trivial:
launch app from icon
do not close it, just switch to another app
launch app from icon again
I founded article in blackberry's forum about it , but I can't find solution where I should remove my ApplicationMenuItem: it added on phone boot and should show all the time.
My code:
public class Jingu extends UiApplication {
public static void main(String[] args) {
ApplicationManager app = ApplicationManager.getApplicationManager();
boolean keepGoing = true;
while (keepGoing) {
if (app.inStartup()) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
} else {
keepGoing = false;
}
}
Jingu theApp = new Jingu();
theApp.initMenuItem();
theApp.showMainScreen();
theApp.enterEventDispatcher();
}
public Jingu() {
}
public void showMainScreen() {
showScreen(new JinguMainScreen(this));
}
public void initMenuItem() {
// Create menu item
Object o = RuntimeStore.getRuntimeStore().get(JinguMenuItem.MY_MENU_ID);
// register only if not done already.
if (o == null) {
new JinguMenuItem(this).registerInstance();
}
}
public void showScreen(Screen aScreen) {
synchronized (Application.getEventLock()) {
try {
UiApplication.getUiApplication().popScreen(aScreen);
} catch (Exception e) {
}
UiApplication.getUiApplication().pushScreen(aScreen);
}
}
}
public class JinguMenuItem extends ApplicationMenuItem {
public static final long MY_MENU_ID = 0xb9739d5240d5943dL;
private final Jingu jingu;
public JinguMenuItem(Jingu jingu) {
super(0x350100);
this.jingu = jingu;
}
public void registerInstance() {
Object menuItem = RuntimeStore.getRuntimeStore().remove(MY_MENU_ID);
if (menuItem == null) {
ApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance();
amir.addMenuItem(ApplicationMenuItemRepository.MENUITEM_SYSTEM, this);
RuntimeStore.getRuntimeStore().put(MY_MENU_ID, this);
}
}
public Object run(Object context) {
jingu.setDefaultFont(Font.getDefault());
jingu.setMainApp(false);
jingu.setBbmEditField(null);
jingu.showMainScreen();
return context;
}
public String toString() {
return "My Menu";
}
}
plz advice where I should delete ApplicationMenuItem in my app?
my regards,
Vadim
If you are registering an ApplicationMenuItem from your application, as a user I would consider it bad style for your application to remove and exit, even if RIM provided a way to do this. You may want to separate your application into two parts. One provides the minimal support for responding to the ApplicationMenuItem selection, that starts automatically and runs in the background. The other has all the rest and can run and exit as needed.
My solution for this situation is:
create alternative entry point and run it on app load
register menu in it
do not use runtimeStore

Resources