Search Results

Search found 2946 results on 118 pages for 'ex umbris'.

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

  • How do I handle all the exceptions in a C# class where both ctor and finalizer throw exceptions?

    - by Frank
    How can I handle all exceptions for a class similar to the following under certain circumstances? class Test : IDisposable { public Test() { throw new Exception("Exception in ctor"); } public void Dispose() { throw new Exception("Exception in Dispose()"); } ~Test() { this.Dispose(); } } I tried this but it doesn't work: static void Main() { Test t = null; try { t = new Test(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } // t is still null } I have also tried to use "using" but it does not handle the exception thrown from ~Test(); static void Main() { try { using (Test t = new Test()) { } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } Any ideas how can I work around?

    Read the article

  • how to make IXMLHTTPRequest work over HTTPS, client being WinCE

    - by siddharth
    hi, i am creating a client, which uploads to and dowloads from WinCE client. the code works properly for HTTP but not for HTTPS. Can any one help me about the changes that needs to be done. Code of client on PC : private void btnUpload_Click(object sender, EventArgs e) { try { MSXML2.DOMDocument xmlDOM = new DOMDocumentClass(); xmlDOM.load(txtUpload.Text); MSXML2.IXMLHTTPRequest x = new XMLHTTPClass(); x.open("POST", "http://192.168.1.12/server.asp?cmd=1", false, "", ""); x.send(xmlDOM); string result = x.responseText; if (x.status == 200) { MessageBox.Show(result); MessageBox.Show("upload file successfully"); } else { MessageBox.Show("upload file unsuccessful"); MessageBox.Show(x.status.ToString() + "\n" + x.statusText); } } catch(Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.Data); } } private void btnDownload_Click(object sender, EventArgs e) { try { HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://192.168.1.12/server.asp?cmd=2"); WebReq.Method = "GET"; HttpWebResponse WebResp = null; WebResp = (HttpWebResponse)WebReq.GetResponse(); Stream myResponseStream = WebResp.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream); string s = myStreamReader.ReadToEnd(); MessageBox.Show(s); StreamWriter SW; SW = File.CreateText(txtDownload.Text); SW.WriteLine(s); SW.Close(); MessageBox.Show(@"save file at" + txtDownload.Text); myStreamReader.Close(); myResponseStream.Close(); WebResp.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.Data); } The client asp page that acts according to the command is : On Error Resume Next Response.Expires = 0 Dim cmd cmd = Request.QueryString("cmd") if cmd = "2" Then Dim xml_dom1 set xml_dom1 = CreateObject("MSXML2.DOMDocument") xml_dom1.load("\Windows\Config.xml") '(Server.MapPath("Config.xml")) Response.Write(xml_dom1.xml) set xml_dom1 = nothing end if if cmd = "1" Then dim xml_dom set xml_dom = CreateObject("MSXML2.DOMDocument") xml_dom.load(request) xml_dom.save("\Windows\Config.xml") set xml_dom = Nothing end if If err.number < 0 Then Response.Write(err.Description) Response.Write(err.number) End If

    Read the article

  • Display\Capture InnerException Message

    - by madlan
    I was using the following to provide more information on a common exception that can occour in a piece of my code, the only problem is this errors if an exception is generated that has no InnerException message. Catch ex As Exception 'MessageBox.Show(ex.Message) 'If there is no InnerException. MessageBox.Show(ex.InnerException.InnerException.Message) End Try Is there a better method of doing this?

    Read the article

  • VB.net Excel sorting

    - by Lora
    I am trying to get a macro convert from VBA over to vb.net and I am getting a type mismatched error and can't figure it out. I am hoping someone here will be able to help me. This is the code. Sub SortRawData() Dim oSheet As Excel.Worksheet Dim oRange As Excel.Range Try oSheet = SetActiveSheet(mLocalDocument, "Sheet 1") oRange = mApplication.ActiveSheet.UsedRange oRange.Sort(Key1:=oRange("J2"), Order1:=Excel.XlSortOrder.xlAscending, _ Header:=Excel.XlYesNoGuess.xlYes, OrderCustom:=1, MatchCase:=False, _ Orientation:=Excel.XlSortOrientation.xlSortColumns, _ DataOption1:=Excel.XlSortDataOption.xlSortNormal, _ DataOption2:=Excel.XlSortDataOption.xlSortNormal, _ DataOption3:=Excel.XlSortDataOption.xlSortNormal) Catch ex As Exception ErrorHandler.HandleError(ex.Message, ex.Source, ex.StackTrace) End Try End Sub This is the code from the macro Sub SortRawData(ByRef poRange As Range) Set poRange = Application.ActiveSheet.UsedRange poRange.Sort Key1:=Range("J2"), Order1:=xlAscending _ , Header:=xlYes, OrderCustom:=1, MatchCase:=False, Orientation:= _ xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, _ DataOption3:=xlSortNormal poRange.Sort Key1:=Range("D2"), Order1:=xlAscending, _ Key2:=Range("H2"), Order2:=xlAscending, _ Key3:=Range("L2"), Order3:=xlAscending, _ Header:=xlYes, OrderCustom:=1, MatchCase:=False, Orientation:= _ xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, _ DataOption3:=xlSortNormal End Sub Any help would be appreciated. Thanks!

    Read the article

  • Keep Hibernate Initializer from Crashing Program

    - by manyxcxi
    I have a Java program using a basic Hibernate session factory. I had an issue with a hibernate hbm.xml mapping file and it crashed my program even though I had the getSessionFactory() call in a try catch try { session = SessionFactoryUtil.getSessionFactory().openStatelessSession(); session.beginTransaction(); rh = getRunHistoryEntry(session); if(rh == null) { throw new Exception("No run history information found in the database for run id " + runId_ + "!"); } } catch(Exception ex) { logger.error("Error initializing hibernate"); } It still manages to break out of this try/catch and crash the main thread. How do I keep it from doing this? The main issue is I have a bunch of cleanup commands that NEED to be run before the main thread shuts down and need to be able to guarantee that even after a failure it still cleans up and goes down somewhat gracefully. The session factory looks like this: public class SessionFactoryUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { try { return sessionFactory; } catch(Exception ex) { return null; } } }

    Read the article

  • Can't get InputStream read to block...

    - by mark dufresne
    I would like the input stream read to block instead of reading end of stream (-1). Is there a way to configure the stream to do this? Here's my Servlet code: PrintWriter out = response.getWriter(); BufferedReader in = request.getReader(); try { String line; int loop = 0; while (loop < 20) { line = in.readLine(); lgr.log(Level.INFO, line); out.println("<" + loop + "html>"); Thread.sleep(1000); loop++; // } } catch (InterruptedException ex) { lgr.log(Level.SEVERE, null, ex); } finally { out.close(); } Here's my Midlet code: private HttpConnection conn; InputStream is; OutputStream os; private boolean exit = false; public void run() { String url = "http://localhost:8080/WebApplication2/NewServlet"; try { conn = (HttpConnection) Connector.open(url); is = conn.openInputStream(); os = conn.openOutputStream(); StringBuffer sb = new StringBuffer(); int c; while (!exit) { os.write("<html>\n".getBytes()); while ((c = is.read()) != -1) { sb.append((char) c); } System.out.println(sb.toString()); sb.delete(0, sb.length() - 1); try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } os.close(); is.close(); conn.close(); } catch (IOException ex) { ex.printStackTrace(); } } I've tried InputStream.read, but it doesn't block either, it returns -1 as well. I'm trying to keep the I/O streams on either side alive. I want the servlet to wait for input, process the input, then send back a response. In the code above it should do this 20 times. thanks for any help

    Read the article

  • Adding/removing session variables on Page OnInit/OnLoad in C#

    - by MKS
    Hi Guys, I am using C#. I am having below code in C#: protected override void OnInit(EventArgs e) { try { if (Session["boolSignOn"].ToString() == "true".ToString()) { lblPanelOpen.Text = Session["panelOpen"].ToString(); } else { lblPanelOpen.Text = Session["panelOpen"].ToString(); } } catch (Exception ex) { Logger.Error("Error processing request:" + ex.Message); } } protected override void OnLoad(EventArgs e) { try { if (!string.IsNullOrEmpty(Session["panelOpen"].ToString())) { lblPanelOpen.Text = string.Empty; Session.Remove("panelOpen"); } } catch (Exception ex) { Logger.Error("Unable to remove the session variable:" + ex.Message); } } In above code I am having a Session["panelOpen"] variable which is created from another user control and once my page is trying to render, I am storing Session["panelOpen"] in my hidden lblPanelOpen.Text on page OnInit() method, however when page is loaded completely then I am trying to remove the session variable. Please suggest!

    Read the article

  • How do I prevent my form from freezing when it is loading an image from the web at the click of a button?

    - by Vimal Basdeo
    I want to display an image from the web to a panel in another Jframe at the click of a button but whenever I click the button first the image loads and during this time the current form potentially freezes and once the image has loaded the form is displayed with the image.. How can I avoid the situation where my form freezes since it is very irritating My codes :: My current class private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) { try { sendMessage("Query,map,$,start,211,Arsenal,!"); System.out.println(receiveMessage()); } catch (UnknownHostException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex); } client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send); this.setVisible(false); this.dispose(); nextform.setVisible(true); // TODO add your handling code here: } My next class that displays the image public class client_trackedbus extends javax.swing.JFrame { client_planform planform=null; DatagramSocket connection=null; DatagramPacket packet_receive=null; DatagramPacket packet_send=null; JLabel label=null; /** Creates new form client_trackedbus */ public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) { initComponents(); this.planform=planform; this.connection=connection; this.packet_receive=packet_receive; this.packet_send=packet_send; try { displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel()); } catch (MalformedURLException ex) { Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex); } } private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{ URL imageurl=new URL(url); Image image=(Toolkit.getDefaultToolkit().createImage(imageurl)); ImageIcon icon = new ImageIcon(image); label.setIcon(icon); panel.add(label); // System.out.println(panel.getSize().width); this.getContentPane().add(panel); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btn_Exit = new javax.swing.JButton(); btn_Plan = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Public Transport Journey Planner"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 368, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 172, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); jLabel1.setText("Your tracked bus"); btn_Exit.setText("Exit"); btn_Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_ExitActionPerformed(evt); } }); btn_Plan.setText("Plan journey"); btn_Plan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_PlanActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(104, 104, 104) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(65, 65, 65) .addComponent(btn_Plan) .addGap(65, 65, 65) .addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_Exit) .addComponent(btn_Plan)) .addContainerGap(12, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Exitform(); } private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.setVisible(false); this.dispose(); this.planform.setVisible(true); } private void Exitform(){ this.setVisible(false); this.dispose(); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new client_trackedbus().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btn_Exit; private javax.swing.JButton btn_Plan; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration }

    Read the article

  • Why does Java Logging API create so many files?

    - by rgksugan
    I am using java logging api to log errors in my exception. I am writing these errors to a log file. When i run my program i find a lot of files created.There are around 50 files created. Is there any mistake in my code or is it normal? Here goes the code try { logger = Logger.getLogger(Reciever.class.getName()); fileHandler = new FileHandler("Applicationlog.log", true); logger.addHandler(fileHandler); logger.setLevel(Level.ALL); SimpleFormatter formatter = new SimpleFormatter(); fileHandler.setFormatter(formatter); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (SecurityException ex) { logger.log(Level.SEVERE, null, ex); }

    Read the article

  • Can't send smtp email from network using C#, asp.net website

    - by Kaysar
    Hi, I have my code here, it works fine from my home, where my user is administrator, and I am connected to internet via a cable network. But, problem is when I try this code from my work place, it does not work. Shows error: "unable to connect to the remote server" From a different machine in the same network: "A socket operation was attempted to an unreachable network 209.xxx.xx.52:25" I checked with our network admin, and he assured me that all the mail ports are open [25,110, and other ports for gmail]. Then, I logged in with administrative privilege, there was a little improvement, it did not show any error, but the actual email was never received. Please note that, the code was tested from development environment, visual studio 2005 and 2008. Any suggestion will be much appreciated. Thanks in advance try { MailMessage mail_message = new MailMessage("[email protected]", txtToEmail.Text, txtSubject.Text, txtBody.Text); SmtpClient mail_client = new SmtpClient("SMTP.y7mail.com"); NetworkCredential Authentic = new NetworkCredential("[email protected]", "xxxxx"); mail_client.UseDefaultCredentials = true; mail_client.Credentials = Authentic; mail_message.IsBodyHtml = true; mail_message.Priority = MailPriority.High; try { mail_client.Send(mail_message); lblStatus.Text = "Mail Sent Successfully"; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); lblStatus.Text = "Mail Sending Failed\r\n" + ex.Message; } } catch (Exception ex) { lblStatus.Text = "Mail Sending Failed\r\n" + ex.Message; }

    Read the article

  • How can I make this client as a multithread client?

    - by Johanna
    Hi, I have read a lot about multithread client but for this one,I can not make it multithread! would you please help me? public class MainClient implements Runnable{ private static InformationClass info = new InformationClass(); private static Socket c; private static String text; public static String getText() { return text; } public static void setText(String text) { MainClient.text = text; } private static PrintWriter os; private static BufferedReader is; static boolean closed = false; /** * @param args the command line arguments */ public static void main(String[] args) { MainFrame farme = new MainFrame(); farme.setVisible(true); try { c = new Socket("localhost", 5050); os = new PrintWriter(c.getOutputStream(), true); is = new BufferedReader(new InputStreamReader(c.getInputStream())); } catch (UnknownHostException ex) { Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); } } public static void active() { String teXt = MainClient.getText(); System.out.println(teXt); os.println(teXt); try { String line = is.readLine(); System.out.println("Text received: " + line); os.flush(); is.close(); is.close(); c.close(); } catch (IOException ex) { Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); } } } also active method will be called when the client write something on the text area and then clicks on the send button. 2) also i have a question that: in the other class I have this action performed for my send button,does it mean that client is multithread?? private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { new Thread(new Runnable() { @Override public void run() { // This gets run in a background thread String text = jTextArea1.getText(); jTextArea2.append(client.getCurrentName() + " : " + text + "\n"); MainClient.setText(client.getCurrentName() + " : " + text + "\n"); clear(); MainClient.active(); } }).start(); } Last EDIT: this is my active method: public static void active() { String teXt = MainClient.getText(); os.println(teXt); String line = is.readLine(); System.out.println("Text received: " + line); os.flush(); is.close(); is.close(); c.close(); }

    Read the article

  • How do I limit access to a subdomain?

    - by Michael
    I can set up the following: mydomain.com (ex m.com) CNAME points to: mysubdomain.hostingprovider.com (ex s1.h.com) subdomain.mydomain.com (ex s2.m.com) CNAME points to: www.anotherdomain.com (ex a.com) There are files in www.anotherdomain.com/mysubfolder/ that I want mydomain.com to be able to access through the subdomain, but I don't want any of the files on the subdomain to be accessable directly. I have full direct access (ftp) to mydomain.com, but I have opono direct access to www.anotherdomain.com (online booking & shopping cart). Is there anyway to make it so access to subdomain.mydomain.com can only be accessed by mydomain.com?

    Read the article

  • C# Compiler should give warning but doesn't?

    - by Cristi Diaconescu
    Someone on my team tried fixing a 'variable not used' warning in an empty catch clause. try { ... } catch (Exception ex) { } - gives a warning about ex not being used. So far, so good. The fix was something like this: try { ... } catch (Exception ex) { string s = ex.Message; } Seeing this, I thought "Just great, so now the compiler will complain about s not being used." But it doesn't! There are no warnings on that piece of code and I can't figure out why. Any ideas? PS. I know catch-all clauses that mute exceptions are a bad thing, but that's a different topic. I also know the initial warning is better removed by doing something like this, that's not the point either. try { ... } catch (Exception) { } or try { ... } catch { }

    Read the article

  • Java: Embedding Soundbank file in JAR

    - by Pyroclastic
    If I have a soundbank stored in a JAR, how would I load that soundbank into my application using resource loading...? I'm trying to consolidate as much of a MIDI program into the jar file as I can, and the last thing I have to add is the soundbank file I'm using, as users won't have the soundbanks installed. I'm trying to put it into my jar file, and then load it with getResource() in the Class class, but I'm getting an InvalidMidiDataException on a soundbank that I know is valid. Here's the code, it's in the constructor for my synthesizer object: try { synth = MidiSystem.getSynthesizer(); channels = synth.getChannels(); instrument = MidiSystem.getSoundbank(this.getClass().getResource("img/soundbank-mid.gm")).getInstruments(); currentInstrument = instrument[0]; synth.loadInstrument(currentInstrument); synth.open(); } catch (InvalidMidiDataException ex) { System.out.println("FAIL"); instrument = synth.getAvailableInstruments(); currentInstrument = instrument[0]; synth.loadInstrument(currentInstrument); try { synth.open(); } catch (MidiUnavailableException ex1) { Logger.getLogger(MIDISynth.class.getName()).log(Level.SEVERE, null, ex1); } } catch (IOException ex) { Logger.getLogger(MIDISynth.class.getName()).log(Level.SEVERE, null, ex); } catch (MidiUnavailableException ex) { Logger.getLogger(MIDISynth.class.getName()).log(Level.SEVERE, null, ex); }

    Read the article

  • Spring 3 MVC - Form Failure Causes Exception When Reloading JSP

    - by jboyd
    Using Spring 3 MVC, please bear with the long code example, it's quite simple, but I want to make sure all relevant information is posted. Basically here is the use case: There is a registration page, a user can login, OR fill out a registration form. The login form is a simple HTML form, the registration form is a more complicated, Spring bound form that uses a RegistrationFormData bean. Here is the relevant code: UserController.java ... @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(Model model) { model.addAttribute("registrationInfo", new ProfileAdminFormData()); return "login"; } ... @RequestMapping(value = "/login.do", method = RequestMethod.POST) public String doLogin( @RequestParam(value = "userName") String userName, @RequestParam(value = "password") String password, Model model) { logger.info("login.do : userName=" + userName + ", password=" + password); try { getUser().login(userName, password); } catch (UserNotFoundException ex) { logger.error(ex); model.addAttribute("loginError", ex.getWebViewableErrorMessage()); return "login"; } return "redirect:/"; } ... @RequestMapping(value = "/register.do") public String register( @ModelAttribute(value = "registrationInfo") ProfileAdminFormData profileAdminFormData, BindingResult result, Model model) { //todo: redirect if (new RegistrationValidator(profileAdminFormData, result).validate()) { try { User().register(profileAdminFormData); return "index"; } catch (UserException ex) { logger.error(ex); model.addAttribute("registrationErrorMessage", ex.getWebViewableErrorMessage()); return "login"; } } return "login"; } and the JSP: ... <form:form commandName="registrationInfo" action="register.do"> ... So the problem here is that when login fails I get an exception because there is no bean "registrationInfo" in the model attributes. What I need is that regardless of the path through this controller that the "registrationInfo" bean is not null, that way if login fails, as opposed to registration, that bean is still in the model. As you can see I create the registrationInfo object explicitly in my controller in the method bound to "/login", which is what I thought was going to be kind of a setup method" Something doesn't feel right about the "/login" method which sets up the page, but I needed to that in order to get the page to render at all without throwing an exception because there is no "registrationInfo" model attribute, as needed by the form in the JSP

    Read the article

  • 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

  • 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

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