Search Results

Search found 2978 results on 120 pages for 'ex parrot'.

Page 8/120 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Using a general class for execution with try/catch/finally?

    - by antirysm
    I find myself having a lot of this in different methods in my code: try { runABunchOfMethods(); } catch (Exception ex) { logger.Log(ex); } What about creating this: public static class Executor { private static ILogger logger; public delegate void ExecuteThis(); static Executor() { // logger = ...GetLoggerFromIoC(); } public static void Execute(ExecuteThis executeThis) { try { executeThis(); } catch (Exception ex) { logger.Log(ex); } } } And just using it like this: private void RunSomething() { Method1(someClassVar); Method2(someOtherClassVar); } ... Executor.Execute(RunSomething); Are there any downsides to this approach? (You could add Executor-methods and delegates when you want a finally and use generics for the type of Exeception you want to catch...)

    Read the article

  • Problem in Application_Error in Global.asax

    - by mmtemporary
    my problem is User.Identity.Name or Request.Url.AbsoluteUri in exception handling is empty when exception email to me. this is Application_Code: void Application_Error(object sender, EventArgs e) { Server.Transfer("~/errors/default.aspx"); } and this is default.aspx code: protected void Page_Load(object sender, EventArgs e) { if (Server.GetLastError() == null) return; Exception ex = Server.GetLastError().GetBaseException(); if (ex == null) return; string message = string.Format("User: ", User.Identity.Name); message += Environment.NewLine; message += string.Format("AbsoluteUri: ", Request.Url.AbsoluteUri); message += Environment.NewLine; message += string.Format("Form: ", Request.Form.ToString()); message += Environment.NewLine; message += string.Format("QueryString: ", Request.QueryString.ToString()); message += Environment.NewLine; HttpBrowserCapabilities browser = Request.Browser; string s = "Browser Capabilities:\n" + "Type = " + browser.Type + "\n" + "Name = " + browser.Browser + "\n" + "Version = " + browser.Version + "\n" + "Platform = " + browser.Platform + "\n" + "Is Crawler = " + browser.Crawler + "\n" + "Supports Cookies = " + browser.Cookies + "\n" + "Supports JavaScript = " + browser.EcmaScriptVersion.ToString() + "\n" + "\n"; message += s; message += Environment.NewLine; message += ex.ToString(); Exception lastException = (Exception)Application["LastException"]; if (lastException == null || lastException.Message != ex.Message) { Application.Lock(); Application["LastException"] = ex; Application.UnLock(); SiteHelper.SendEmail(SiteHelper.AdministratorEMail, "Error!!!", message, false); } Server.ClearError(); } but i receive email like this (this is header without full exception content): User: AbsoluteUri: Form: QueryString: Browser Capabilities: Type = IE8 Name = IE Version = 8.0 Platform = WinXP Is Crawler = False Supports Cookies = True Supports JavaScript = 1.2 why username and request url is emty? this problem is exist when i replace transfer with redirect or i don't use both. tanx

    Read the article

  • VB .NET error handling, pass error to caller

    - by user1375452
    this is my very first project on vb.net and i am now struggling to migrate a vba working add in to a vb.net COM Add-in. I think i'm sort of getting the hang, but error handling has me stymied. This is a test i've been using to understand the try-catch and how to pass exception to caller Public Sub test() Dim ActWkSh As Excel.Worksheet Dim ActRng As Excel.Range Dim ActCll As Excel.Range Dim sVar01 As String Dim iVar01 As Integer Dim sVar02 As String Dim iVar02 As Integer Dim objVar01 As Object ActWkSh = Me.Application.ActiveSheet ActRng = Me.Application.Selection ActCll = Me.Application.ActiveCell iVar01 = iVar02 = 1 sVar01 = CStr(ActCll.Value) sVar02 = CStr(ActCll.Offset(1, 0).Value) Try objVar01 = GetValuesV(sVar01, sVar02) 'DO SOMETHING HERE Catch ex As Exception MsgBox("ERRORE: " + ex.Message) 'LOG ERROR SOMEWHERE Finally MsgBox("DONE!") End Try End Sub Private Function GetValuesV(ByVal QryStr As Object, ByVal qryConn As String) As Object Dim cnn As Object Dim rs As Object Try cnn = CreateObject("ADODB.Connection") cnn.Open(qryConn) rs = CreateObject("ADODB.recordset") rs = cnn.Execute(QryStr) If rs.EOF = False Then GetValuesV = rs.GetRows Else Throw New System.Exception("Query Return Empty Set") End If Catch ex As Exception Throw ex Finally rs.Close() cnn.Close() End Try End Function i'd like to have the error message up to test, but MsgBox("ERRORE: " + ex.Message) pops out something unexpected (Object variable or With block variable not set) What am i doing wrong here?? Thanks D

    Read the article

  • Exceptions not being caught

    - by Thomas Freudenberg
    We have following code: try { // some code throwing MyException } catch (MyException ex) { // [1] // no (re)throw here } catch (Exception ex) { if (ex is MyException) { // [2] } } If we run the code without a debugger attached, everything runs fine. However, IF we debug the code, we don't get to point [1] but [2]. As far as I understand the language specification this should not be possible. Even weirder, this code used run fine even while debugging. The strange behavior started only a few days ago.

    Read the article

  • Correct way to close database connection in event of exception.

    - by lowlyintern
    /I have some code of of the following form. Does this mean the connection is left open if there is an exception? Note, I am using a Microsoft SQL compact edition database./ try { SqlCeConnection conn = new SqlCeConnection(ConnectionString); conn.Open(); using (SqlCeCommand cmd = new SqlCeCommand("SELECT stuff FROM SomeTable", conn)) { // do some stuff } conn.Close(); } catch (Exception ex) { ExceptionManager.HandleException(ex); } /*Surely a better way would be to declare a connection object before the try, establish a connection inside the try block and close it in a finally block? */ SqlCeConnection conn = null; try { conn = new SqlCeConnection(ConnectionString); conn.Open(); using (SqlCeCommand cmd = new SqlCeCommand("SELECT stuff FROM SomeTable", conn)) { // do some stuff } } catch (Exception ex) { ExceptionManager.HandleException(ex); } finally { if( conn != null ) conn.Close(); }

    Read the article

  • Better way to ignore exception type: multiple catch block vs. type querying

    - by HuBeZa
    There are situations that we like to ignore a specific exception type (commonly ObjectDisposedException). It can be achieved with those two methods: try { // code that throws error here: } catch (SpecificException) { /*ignore this*/ } catch (Exception ex) { // Handle exception, write to log... } or try { // code that throws error here: } catch (Exception ex) { if (ex is SpecificException) { /*ignore this*/ } else { // Handle exception, write to log... } } What are the pros and cons of this two methods (regarding performance, readability, etc.)?

    Read the article

  • Why is TargetInvocationException treated as uncaught by the IDE?

    - by Jason Coyne
    I have some code that is using reflection to pull property values from an object. In some cases the properties may throw exceptions, because they have null references etc. try { child.Target = propertyInfo.GetValue(target, null); } catch (TargetInvocationException ex) { child.Target = ex.InnerException.Message; } catch (Exception ex) { child.Target = ex.Message; } Ultimately the code works correctly, however when I am running under the debugger : When the property throws an exception, the IDE drops into the debugger as if the exception was uncaught. If I just hit run, the program flows through and the exception comes out as a TargetInvocationException with the real exception in the InnerException property. How can I stop this from happening?

    Read the article

  • Java programming accessing object variables

    - by Haxed
    Helo, there are 3 files, CustomerClient.java, CustomerServer.java and Customer.java PROBLEM: In the CustomerServer.java file, i get an error when I compile the CustomerServer.java at line : System.out.println(a[k].getName()); ERROR: init: deps-jar: Compiling 1 source file to C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\build\classes C:\Documents and Settings\TLNA\My Documents\NetBeansProjects\Server\src\CustomerServer.java:44: cannot find symbol symbol : method getName() location: class Customer System.out.println(a[k].getName()); 1 error BUILD FAILED (total time: 0 seconds) CustomerClient.java import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CustomerClient extends JApplet { private JTextField jtfName = new JTextField(32); private JTextField jtfSeatNo = new JTextField(32); // Button for sending a student to the server private JButton jbtRegister = new JButton("Register to the Server"); // Indicate if it runs as application private boolean isStandAlone = false; // Host name or ip String host = "localhost"; public void init() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(2, 1)); p1.add(new JLabel("Name")); p1.add(jtfName); p1.add(new JLabel("Seat No.")); p1.add(jtfSeatNo); add(p1, BorderLayout.CENTER); add(jbtRegister, BorderLayout.SOUTH); // Register listener jbtRegister.addActionListener(new ButtonListener()); // Find the IP address of the Web server if (!isStandAlone) { host = getCodeBase().getHost(); } } /** Handle button action */ private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { // Establish connection with the server Socket socket = new Socket(host, 8000); // Create an output stream to the server ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); // Get text field String name = jtfName.getText().trim(); String seatNo = jtfSeatNo.getText().trim(); // Create a Student object and send to the server Customer s = new Customer(name, seatNo); toServer.writeObject(s); } catch (IOException ex) { System.err.println(ex); } } } /** Run the applet as an application */ public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Register Student Client"); // Create an instance of the applet CustomerClient applet = new CustomerClient(); applet.isStandAlone = true; // Get host if (args.length == 1) { applet.host = args[0]; // Add the applet instance to the frame } frame.add(applet, BorderLayout.CENTER); // Invoke init() and start() applet.init(); applet.start(); // Display the frame frame.pack(); frame.setVisible(true); } } CustomerServer.java import java.io.*; import java.net.*; public class CustomerServer { private String name; private int i; private ObjectOutputStream outputToFile; private ObjectInputStream inputFromClient; public static void main(String[] args) { new CustomerServer(); } public CustomerServer() { Customer[] a = new Customer[30]; try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); System.out.println("Server started "); // Create an object ouput stream outputToFile = new ObjectOutputStream( new FileOutputStream("student.dat", true)); while (true) { // Listen for a new connection request Socket socket = serverSocket.accept(); // Create an input stream from the socket inputFromClient = new ObjectInputStream(socket.getInputStream()); // Read from input //Object object = inputFromClient.readObject(); for (int k = 0; k <= 2; k++) { if (a[k] == null) { a[k] = (Customer) inputFromClient.readObject(); // Write to the file outputToFile.writeObject(a[k]); //System.out.println("A new student object is stored"); System.out.println(a[k].getName()); break; } if (k == 2) { //fully booked outputToFile.writeObject("All seats are booked"); break; } } } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inputFromClient.close(); outputToFile.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } Customer.java public class Customer implements java.io.Serializable { private String name; private String seatno; public Customer(String name, String seatno) { this.name = name; this.seatno = seatno; } public String getName() { return name; } public String getSeatNo() { return seatno; } }

    Read the article

  • HttpsURLConnection failing intermittently to the same URL

    - by Arkaitz Jimenez
    I think I'm experiencing the same as http://groups.google.com/group/android-developers/msg/9d37d64aad0ee357 This is Android 1.5 SDK. I happen to call several times below code(which is in a method) with the same url and it fails intermittently. When it fails, there is no exception, the stream is empty so the readConnection fails, and getResponseCode returns -1. Global caching is disabled, setDefaultUseCaches(false); I suppose there must be some kind of url connection object pool somewhere. Any idea on how can I workaround this? HttpURLConnection connection = null; try { URL url = new URL(this.url); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "basic " + Base64Coder.encodeString(user + ":" + password)); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); readConnection(connection.getInputStream()); connection.disconnect(); } catch (IOException ex) { reportException(ex, connection.getResponseCode()) } catch (ParserException ex) { reportException(ex, connection.getResponseCode()) }

    Read the article

  • Fix for Visual Studio 2005 not showing filename or line on errors in web pages when compiling?

    - by spoulson
    A project I'm on requires Visual Studio 2005. One annoyance is that when a website project in the solution, any compile errors from .aspx or .ascx files show up like: (0,0): warning CS0168: The variable 'ex' is declared but never used (0,0): warning CS0162: Unreachable code detected (0,0): warning CS0168: The variable 'ex' is declared but never used (0,0): warning CS0168: The variable 'ex' is declared but never used How can I track these down? Is there an option I'm missing that gives me filename and line numbers?

    Read the article

  • Django | How to pass form values to an redirected page

    - by MMRUser
    Here's my function: def check_form(request): if request.method == 'POST': form = UsersForm(request.POST) if form.is_valid(): cd = form.cleaned_data try: newUser = form.save() return HttpResponseRedirect('/testproject/summery/) except Exception, ex: # sys.stderr.write('Value error: %s\n' % str(ex) return HttpResponse("Error %s" % str(ex)) else: return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request)) else: form = CiviguardUsersForm() return render_to_response('index.html',context_instance=RequestContext(request)) I want to pass each and every field in to a page call summery and display all the fields when user submits the form, so then users can view it before confirming the registration. Thanks..

    Read the article

  • not all data insert in convert from excell to database

    - by Gold
    hi i have this code: ConnectString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=\"Excel 12.0 Xml;HDR=No\""; SheetName = SheetName.Substring(0, SheetName.Length - 5); OleDbConnection Connection = new OleDbConnection(); Connection.ConnectionString = ConnectString; try {Connection.Open();} catch (Exception EX) { MessageBox.Show(EX.Message); } OleDbDataAdapter Command = new OleDbDataAdapter("SELECT * FROM [" + SheetName + "$]", Connection); DataSet ExcelData = new DataSet(); try {Command.Fill(ExcelData);} catch (Exception EX) { MessageBox.Show(EX.Message); } finally { if (Connection.State != ConnectionState.Closed) Connection.Close(); } but not all the data in column 1 insert - i get empty data why ? what can be wrong ? thank's in advance

    Read the article

  • UnknownHostException in java (that too only sometimes)

    - by Nitesh Panchal
    Hello, I am trying to read rss feed of Yahoo but i am unable to make it work properly. The code is absolutely correct , i am sure about it. It works sometimes but sometimes i get UnknownHostException. What can be the reason? Is there some problem with my internet or something else? This is my code :- public List<RssFeed> getRssFeed() { try { List<RssFeed> objList = new ArrayList<RssFeed>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse("http://rss.news.yahoo.com/rss/india"); //doc.getDocumentElement().normalize(); Element docElement = doc.getDocumentElement(); NodeList objChannelList = docElement.getChildNodes(); for (int intIndex = 0; intIndex < objChannelList.getLength(); intIndex++) { if (objChannelList.item(intIndex).getNodeType() == Node.ELEMENT_NODE) { Element elemItem = (Element) objChannelList.item(intIndex); NodeList itemList = elemItem.getElementsByTagName("item"); //show only 3 news int count = itemList.getLength() > 3 ? 3 : objChannelList.getLength(); for (int intSubIndex = 0; intSubIndex < count; intSubIndex++) { NodeList itemDetailList = itemList.item(intSubIndex).getChildNodes(); String strTitle = ((Node) itemDetailList.item(RSS_VALUES.TITLE.getValue())).getFirstChild().getNodeValue(); String strdescription = ((Node) itemDetailList.item(RSS_VALUES.DESCRIPTION.getValue())).getFirstChild().getNodeValue(); String strLink = ((Node) itemDetailList.item(RSS_VALUES.LINK.getValue())).getFirstChild().getNodeValue(); //System.out.println(strTitle + "\n" + strdescription + "\n" + strLink + "\n\n\n\n"); objList.add(new RssFeed(strTitle, strdescription, strLink)); } } } return objList; } catch (SAXException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } return null; } Thanks in advance :). This problem has been bugging me since 1 month. Don't know why does Java in this case behave as per its mood :(

    Read the article

  • Refactor This (Ugly Code)!

    - by Alois Kraus
    Ayende has put on his blog some ugly code to refactor. First and foremost it is nearly impossible to reason about other peoples code without knowing the driving forces behind the current code. It is certainly possible to make it much cleaner when potential sources of errors cannot happen in the first place due to good design. I can see what the intention of the code is but I do not know about every brittle detail if I am allowed to reorder things here and there to simplify things. So I decided to make it much simpler by identifying the different responsibilities of the methods and encapsulate it in different classes. The code we need to refactor seems to deal with a handler after a message has been sent to a message queue. The handler does complete the current transaction if there is any and does handle any errors happening there. If during the the completion of the transaction errors occur the transaction is at least disposed. We can enter the handler already in a faulty state where we try to deliver the complete event in any case and signal a failure event and try to resend the message again to the queue if it was not inside a transaction. All is decorated with many try/catch blocks, duplicated code and some state variables to route the program flow. It is hard to understand and difficult to reason about. In other words: This code is a mess and could be written by me if I was under pressure. Here comes to code we want to refactor:         private void HandleMessageCompletion(                                      Message message,                                      TransactionScope tx,                                      OpenedQueue messageQueue,                                      Exception exception,                                      Action<CurrentMessageInformation, Exception> messageCompleted,                                      Action<CurrentMessageInformation> beforeTransactionCommit)         {             var txDisposed = false;             if (exception == null)             {                 try                 {                     if (tx != null)                     {                         if (beforeTransactionCommit != null)                             beforeTransactionCommit(currentMessageInformation);                         tx.Complete();                         tx.Dispose();                         txDisposed = true;                     }                     try                     {                         if (messageCompleted != null)                             messageCompleted(currentMessageInformation, exception);                     }                     catch (Exception e)                     {                         Trace.TraceError("An error occured when raising the MessageCompleted event, the error will NOT affect the message processing"+ e);                     }                     return;                 }                 catch (Exception e)                 {                     Trace.TraceWarning("Failed to complete transaction, moving to error mode"+ e);                     exception = e;                 }             }             try             {                 if (txDisposed == false && tx != null)                 {                     Trace.TraceWarning("Disposing transaction in error mode");                     tx.Dispose();                 }             }             catch (Exception e)             {                 Trace.TraceWarning("Failed to dispose of transaction in error mode."+ e);             }             if (message == null)                 return;                 try             {                 if (messageCompleted != null)                     messageCompleted(currentMessageInformation, exception);             }             catch (Exception e)             {                 Trace.TraceError("An error occured when raising the MessageCompleted event, the error will NOT affect the message processing"+ e);             }               try             {                 var copy = MessageProcessingFailure;                 if (copy != null)                     copy(currentMessageInformation, exception);             }             catch (Exception moduleException)             {                 Trace.TraceError("Module failed to process message failure: " + exception.Message+                                              moduleException);             }               if (messageQueue.IsTransactional == false)// put the item back in the queue             {                 messageQueue.Send(message);             }         }     You can see quite some processing and handling going on there. Yes this looks like real world code one did put together to make things work and he does not trust his callbacks. I guess these are event handlers which are optional and the delegates were extracted from an event to call them back later when necessary.  Lets see what the author of this code did intend:          private void HandleMessageCompletion(             TransactionHandler transactionHandler,             MessageCompletionHandler handler,             CurrentMessageInformation messageInfo,             ErrorCollector errors             )         {               // commit current pending transaction             transactionHandler.CallHandlerAndCommit(messageInfo, errors);               // We have an error for a null message do not send completion event             if (messageInfo.CurrentMessage == null)                 return;               // Send completion event in any case regardless of errors             handler.OnMessageCompleted(messageInfo, errors);               // put message back if queue is not transactional             transactionHandler.ResendMessageOnError(messageInfo.CurrentMessage, errors);         }   I did not bother to write the intention here again since the code should be pretty self explaining by now. I have used comments to explain the still nontrivial procedure step by step revealing the real intention about all this complex program flow. The original complexity of the problem domain does not go away but by applying the techniques of SRP (Single Responsibility Principle) and some functional style but we can abstract the necessary complexity away in useful abstractions which make it much easier to reason about it. Since most of the method seems to deal with errors I thought it was a good idea to encapsulate the error state of our current message in an ErrorCollector object which stores all exceptions in a list along with a description what the error all was about in the exception itself. We can log it later or not depending on the log level or whatever. It is really just a simple list that encapsulates the current error state.          class ErrorCollector          {              List<Exception> _Errors = new List<Exception>();                public void Add(Exception ex, string description)              {                  ex.Data["Description"] = description;                  _Errors.Add(ex);              }                public Exception Last              {                  get                  {                      return _Errors.LastOrDefault();                  }              }                public bool HasError              {                  get                  {                      return _Errors.Count > 0;                  }              }          }   Since the error state is global we have two choices to store a reference in the other helper objects (TransactionHandler and MessageCompletionHandler)or pass it to the method calls when necessary. I did chose the latter one because a second argument does not hurt and makes it easier to reason about the overall state while the helper objects remain stateless and immutable which makes the helper objects much easier to understand and as a bonus thread safe as well. This does not mean that the stored member variables are stateless or thread safe as well but at least our helper classes are it. Most of the complexity is located the transaction handling I consider as a separate responsibility that I delegate to the TransactionHandler which does nothing if there is no transaction or Call the Before Commit Handler Commit Transaction Dispose Transaction if commit did throw In fact it has a second responsibility to resend the message if the transaction did fail. I did see a good fit there since it deals with transaction failures.          class TransactionHandler          {              TransactionScope _Tx;              Action<CurrentMessageInformation> _BeforeCommit;              OpenedQueue _MessageQueue;                public TransactionHandler(TransactionScope tx, Action<CurrentMessageInformation> beforeCommit, OpenedQueue messageQueue)              {                  _Tx = tx;                  _BeforeCommit = beforeCommit;                  _MessageQueue = messageQueue;              }                public void CallHandlerAndCommit(CurrentMessageInformation currentMessageInfo, ErrorCollector errors)              {                  if (_Tx != null && !errors.HasError)                  {                      try                      {                          if (_BeforeCommit != null)                          {                              _BeforeCommit(currentMessageInfo);                          }                            _Tx.Complete();                          _Tx.Dispose();                      }                      catch (Exception ex)                      {                          errors.Add(ex, "Failed to complete transaction, moving to error mode");                          Trace.TraceWarning("Disposing transaction in error mode");                          try                          {                              _Tx.Dispose();                          }                          catch (Exception ex2)                          {                              errors.Add(ex2, "Failed to dispose of transaction in error mode.");                          }                      }                  }              }                public void ResendMessageOnError(Message message, ErrorCollector errors)              {                  if (errors.HasError && !_MessageQueue.IsTransactional)                  {                      _MessageQueue.Send(message);                  }              }          } If we need to change the handling in the future we have a much easier time to reason about our application flow than before. After we did complete our transaction and called our callback we can call the completion handler which is the main purpose of the HandleMessageCompletion method after all. The responsiblity o the MessageCompletionHandler is to call the completion callback and the failure callback when some error has occurred.            class MessageCompletionHandler          {              Action<CurrentMessageInformation, Exception> _MessageCompletedHandler;              Action<CurrentMessageInformation, Exception> _MessageProcessingFailure;                public MessageCompletionHandler(Action<CurrentMessageInformation, Exception> messageCompletedHandler,                                              Action<CurrentMessageInformation, Exception> messageProcessingFailure)              {                  _MessageCompletedHandler = messageCompletedHandler;                  _MessageProcessingFailure = messageProcessingFailure;              }                  public void OnMessageCompleted(CurrentMessageInformation currentMessageInfo, ErrorCollector errors)              {                  try                  {                      if (_MessageCompletedHandler != null)                      {                          _MessageCompletedHandler(currentMessageInfo, errors.Last);                      }                  }                  catch (Exception ex)                  {                      errors.Add(ex, "An error occured when raising the MessageCompleted event, the error will NOT affect the message processing");                  }                    if (errors.HasError)                  {                      SignalFailedMessage(currentMessageInfo, errors);                  }              }                void SignalFailedMessage(CurrentMessageInformation currentMessageInfo, ErrorCollector errors)              {                  try                  {                      if (_MessageProcessingFailure != null)                          _MessageProcessingFailure(currentMessageInfo, errors.Last);                  }                  catch (Exception moduleException)                  {                      errors.Add(moduleException, "Module failed to process message failure");                  }              }            }   If for some reason I did screw up the logic and we need to call the completion handler from our Transaction handler we can simple add to the CallHandlerAndCommit method a third argument to the MessageCompletionHandler and we are fine again. If the logic becomes even more complex and we need to ensure that the completed event is triggered only once we have now one place the completion handler to capture the state. During this refactoring I simple put things together that belong together and came up with useful abstractions. If you look at the original argument list of the HandleMessageCompletion method I have put many things together:   Original Arguments New Arguments Encapsulate Message message CurrentMessageInformation messageInfo         Message message TransactionScope tx Action<CurrentMessageInformation> beforeTransactionCommit OpenedQueue messageQueue TransactionHandler transactionHandler        TransactionScope tx        OpenedQueue messageQueue        Action<CurrentMessageInformation> beforeTransactionCommit Exception exception,             ErrorCollector errors Action<CurrentMessageInformation, Exception> messageCompleted MessageCompletionHandler handler          Action<CurrentMessageInformation, Exception> messageCompleted          Action<CurrentMessageInformation, Exception> messageProcessingFailure The reason is simple: Put the things that have relationships together and you will find nearly automatically useful abstractions. I hope this makes sense to you. If you see a way to make it even more simple you can show Ayende your improved version as well.

    Read the article

  • How can rotating release managers improve a project's velocity and stability?

    - by Yannis Rizos
    The Wikipedia article on Parrot VM includes this unreferenced claim: Core committers take turns producing releases in a revolving schedule, where no single committer is responsible for multiple releases in a row. This practice has improved the project's velocity and stability. Parrot's Release Manager role documentation doesn't offer any further insight into the process, and I couldn't find any reference for the claim. My first thoughts were that rotating release managers seems like a good idea, sharing the responsibility between as many people as possible, and having a certain degree of polyphony in releases. Is it, though? Rotating release managers has been proposed for Launchpad, and there were some interesting counterarguments: Release management is something that requires a good understanding of all parts of the code and the authority to make calls under pressure if issues come up during the release itself The less change we can have to the release process the better from an operational perspective Don't really want an engineer to have to learn all this stuff on the job as well as have other things to take care of (regular development responsibilities) Any change of timezones of the releases would need to be approved with the SAs and: I think this would be a great idea (mainly because of my lust for power), but I also think that there should be some way making sure that a release manager doesn't get overwhelmed if something disastrous happens during release week, maybe by have a deputy release manager at the same time (maybe just falling back to Francis or Kiko would be sufficient). The practice doesn't appear to be very common, and the counterarguments seem reasonalbe and convincing. I'm quite confused on how it would improve a project's velocity and stability, is there something I'm missing, or is this just a bad edit on the Wikipedia article? Worth noting that the top voted answer in the related "Is rotating the lead developer a good or bad idea?" question boldly notes: Don't rotate.

    Read the article

  • Enterprise Library Logging / Exception handling and Postsharp

    - by subodhnpushpak
    One of my colleagues came-up with a unique situation where it was required to create log files based on the input file which is uploaded. For example if A.xml is uploaded, the corresponding log file should be A_log.txt. I am a strong believer that Logging / EH / caching are cross-cutting architecture aspects and should be least invasive to the business-logic written in enterprise application. I have been using Enterprise Library for logging / EH (i use to work with Avanade, so i have affection towards the library!! :D ). I have been also using excellent library called PostSharp for cross cutting aspect. Here i present a solution with and without PostSharp all in a unit test. Please see full source code at end of the this blog post. But first, we need to tweak the enterprise library so that the log files are created at runtime based on input given. Below is Custom trace listner which writes log into a given file extracted out of Logentry extendedProperties property. using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using Microsoft.Practices.EnterpriseLibrary.Logging; using System.IO; using System.Text; using System; using System.Diagnostics;   namespace Subodh.Framework.Logging { [ConfigurationElementType(typeof(CustomTraceListenerData))] public class LogToFileTraceListener : CustomTraceListener {   private static object syncRoot = new object();   public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {   if ((data is LogEntry) & this.Formatter != null) { WriteOutToLog(this.Formatter.Format((LogEntry)data), (LogEntry)data); } else { WriteOutToLog(data.ToString(), (LogEntry)data); } }   public override void Write(string message) { Debug.Print(message.ToString()); }   public override void WriteLine(string message) { Debug.Print(message.ToString()); }   private void WriteOutToLog(string BodyText, LogEntry logentry) { try { //Get the filelocation from the extended properties if (logentry.ExtendedProperties.ContainsKey("filelocation")) { string fullPath = Path.GetFullPath(logentry.ExtendedProperties["filelocation"].ToString());   //Create the directory where the log file is written to if it does not exist. DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(fullPath));   if (directoryInfo.Exists == false) { directoryInfo.Create(); }   //Lock the file to prevent another process from using this file //as data is being written to it.   lock (syncRoot) { using (FileStream fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.Write, 4096, true)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { Log(BodyText, sw); sw.Close(); } fs.Close(); } } } } catch (Exception ex) { throw new LoggingException(ex.Message, ex); } }   /// <summary> /// Write message to named file /// </summary> public static void Log(string logMessage, TextWriter w) { w.WriteLine("{0}", logMessage); } } }   The above can be “plugged into” the code using below configuration <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Trace" logWarningsWhenNoCategoriesMatch="true"> <listeners> <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Subodh.Framework.Logging.LogToFileTraceListener, Subodh.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Subodh Custom Trace Listener" initializeData="" formatter="Text Formatter" /> </listeners> Similarly we can use PostSharp to expose the above as cross cutting aspects as below using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using PostSharp.Laos; using System.Diagnostics; using GC.FrameworkServices.ExceptionHandler; using Subodh.Framework.Logging;   namespace Subodh.Framework.ExceptionHandling { [Serializable] public sealed class LogExceptionAttribute : OnExceptionAspect { private string prefix; private MethodFormatStrings formatStrings;   // This field is not serialized. It is used only at compile time. [NonSerialized] private readonly Type exceptionType; private string fileName;   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception flowing out of the methods to which /// the custom attribute is applied. /// </summary> public LogExceptionAttribute() { }   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception derived from a given <see cref="Type"/> /// flowing out of the methods to which /// the custom attribute is applied. /// </summary> /// <param name="exceptionType"></param> public LogExceptionAttribute( Type exceptionType ) { this.exceptionType = exceptionType; }   public LogExceptionAttribute(Type exceptionType, string fileName) { this.exceptionType = exceptionType; this.fileName = fileName; }   /// <summary> /// Gets or sets the prefix string, printed before every trace message. /// </summary> /// <value> /// For instance <c>[Exception]</c>. /// </value> public string Prefix { get { return this.prefix; } set { this.prefix = value; } }   /// <summary> /// Initializes the current object. Called at compile time by PostSharp. /// </summary> /// <param name="method">Method to which the current instance is /// associated.</param> public override void CompileTimeInitialize( MethodBase method ) { // We just initialize our fields. They will be serialized at compile-time // and deserialized at runtime. this.formatStrings = Formatter.GetMethodFormatStrings( method ); this.prefix = Formatter.NormalizePrefix( this.prefix ); }   public override Type GetExceptionType( MethodBase method ) { return this.exceptionType; }   /// <summary> /// Method executed when an exception occurs in the methods to which the current /// custom attribute has been applied. We just write a record to the tracing /// subsystem. /// </summary> /// <param name="context">Event arguments specifying which method /// is being called and with which parameters.</param> public override void OnException( MethodExecutionEventArgs context ) { string message = String.Format("{0}Exception {1} {{{2}}} in {{{3}}}. \r\n\r\nStack Trace {4}", this.prefix, context.Exception.GetType().Name, context.Exception.Message, this.formatStrings.Format(context.Instance, context.Method, context.GetReadOnlyArgumentArray()), context.Exception.StackTrace); if(!string.IsNullOrEmpty(fileName)) { ApplicationLogger.LogException(message, fileName); } else { ApplicationLogger.LogException(message, Source.UtilityService); } } } } To use the above below is the unit test [TestMethod] [ExpectedException(typeof(NotImplementedException))] public void TestMethod1() { MethodThrowingExceptionForLog(); try { MethodThrowingExceptionForLogWithPostSharp(); } catch (NotImplementedException ex) { throw ex; } }   private void MethodThrowingExceptionForLog() { try { throw new NotImplementedException(); } catch (NotImplementedException ex) { // create file and then write log ApplicationLogger.TraceMessage("this is a trace message which will be logged in Test1MyFile", @"D:\EL\Test1Myfile.txt"); ApplicationLogger.TraceMessage("this is a trace message which will be logged in YetAnotherTest1Myfile", @"D:\EL\YetAnotherTest1Myfile.txt"); } }   // Automatically log details using attributes // Log exception using attributes .... A La WCF [FaultContract(typeof(FaultMessage))] style] [Log(@"D:\EL\Test1MyfileLogPostsharp.txt")] [LogException(typeof(NotImplementedException), @"D:\EL\Test1MyfileExceptionPostsharp.txt")] private void MethodThrowingExceptionForLogWithPostSharp() { throw new NotImplementedException(); } The good thing about the approach is that all the logging and EH is done at centralized location controlled by PostSharp. Of Course, if some other library has to be used instead of EL, it can easily be plugged in. Also, the coder ARE ONLY involved in writing business code in methods, which makes code cleaner. Here is the full source code. The third party assemblies provided are from EL and PostSharp and i presume you will find these useful. Do let me know your thoughts / ideas on the same. Technorati Tags: PostSharp,Enterprize library,C#,Logging,Exception handling

    Read the article

  • Professional Custom Logo Design vs. Mr. Right

    John is an ex-marine and ex-employee of general motors. He recently lost his job working as a welder on the assembly lines of one of GM manufacturing plants. John has traveled a lot and knows a lot a... [Author: Emily Matthew - Web Design and Development - March 31, 2010]

    Read the article

  • Stackify featured in the KC Business Journal

    - by Matt Watson
    Very excited to be in the KC Business Journal today. Stackify is focused on giving limited production access to developers to help them do application troubleshooting. We about ready to launch our product and we are looking for beta testers!Ex-VinSolutions exec pours sale proceeds into Stackify, other tech startupsRead the entire article on their website:http://www.bizjournals.com/kansascity/print-edition/2012/06/01/ex-vinsolutions-exec-pours-sale.html

    Read the article

  • Deselect first row on gridview onload

    - by Suresh Behera
    I had situation to deselect the first gridview row on load and came to know IsSynchronizedWithCurrentItem on Gridview should able to that but some how i missed on gridview. Mean while below one should work void gvMain_RowLoaded( object sender, RowLoadedEventArgs e) { try { GridViewRow row = e.Row as GridViewRow; if (row != null && !firstItemExpanded) { row.DetailsVisibility = Visibility.Collapsed; firstItemExpanded = false ; } } catch (Exception ex) { throw ex; } } .csharpcode, .csharpcode...(read more)

    Read the article

  • multiple project [closed]

    - by user1783508
    I want a application in which I can create multiple project ex illustration [-] project 1 requirement arhitecture design test [-] project 2 requirement arhitecture design test create any Uml diagram Ex illustration add class diagram add use case add etc. and many other feature. In other words, I want an application like eclipse but for software documentation namely requirement, design etc.

    Read the article

  • Viewing the NetBeans Central Registry

    - by Geertjan
    For some fun, create a TopComponent and then add this bit of code, with thanks to Toni Epple: add(new BeanTreeView(), BorderLayout.CENTER); try { myExplorerManager.setRootContext(DataObject.find(FileUtil.getConfigRoot()).getNodeDelegate()); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } Run the application and you'll see the NetBeans Central Registry a.k.a. System FileSystem) of the application you're running.

    Read the article

  • How to fix a Postfix/MySQL/Dovecot Unknown Host Issue?

    - by thiesdiggity
    I am having an issue with one of my Postfix/Dovecot mail servers and I'm unsure how to fix the problem. I will try to explain it in detail, here it goes: I have an Ubuntu server setup using Virtual hosting with Postfix, Dovecot and MySQL. We have one domain setup as a virtual domain, for this example I am going to use mail.example.com. Under that domain we have one email address. I have another server (MS Exchange) setup using another one of my sub-domains, ex.example.com. The problem is that when I SMTP into the account on mail.example.com and try to send an email to an account on ex.example.com, I get the email returned back to us with an "unknown host" error. Now, I know that the mail.example.com server can resolve the ex.example.com domain because I can ping/dig while SSH'd into it. I can also log into Postfix via Telnet and send an email to an ex.example.com mailbox. I'm guessing that it has something to do with Postfix/Dovecot looking locally for the domain in the virtual domain list because of the tld domain (example.com)? If that's the case, how do I get Postfix/Dovecot to only look locally for the entire URL (mail.example.com) and if it doesn't find it, send it to the correct server by looking up the MX/A records (which I know exist and are setup correctly)? I have been working on this all day and any guidance would be GREATLY appreciated! Thanks for your time!

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >