Search Results

Search found 4116 results on 165 pages for 'baron throw'.

Page 12/165 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Using default parameters for 404 error (PHP with mvc design)?

    - by user1175327
    I have a custom made Framework (written in PHP). It all works very good, but i have some doubts about a certain thing. Right now when a user call this url for example: http://host.com/user/edit/12 Which would resolve to: user = userController edit = editAction() in userController 12 = treated as a param But suppose the controller 'userController' doesn't exist. Then i could throw a 404. But on the other hand, the url could also be used as params for the indexController (which is the default controller). So in that case: controller = indexController user = could be an action in indexController, otherwise treated as a param edit = treated as a param 12 = treated as a param That is actually how it works right now in my framework. So basically, i never throw a 404. I could ofcourse say that only params can be given if the controller name is explicitly named in the URL. So if i want the above url: http://host.com/user/edit/12 To be invoked by the indexController, in the indexAction. Then i specifically have to tell what controller and action it uses in the URL. So the URL should become: http://host.com/index/index/user/edit/12 index = indexController index (2nd one) = the action method user = treated as a param edit = treated as a param 12 = treated as a param That way, when a controller doesn't exist, i don't reroute everything as a param to the index controller and simply throw a 404 error. Now my question is, which one is more preffered? Should i allow both options to be configurable in a config file? Or should i always use one of them. Simply because that's the only and best way to do it?

    Read the article

  • Throwing and catching exceptions in the same function/method

    - by usr
    I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them. I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java: private static int sideInput() { int side = 0; String input; Scanner scanner = new Scanner(System.in); do { System.out.print("Side length: "); input = scanner.nextLine(); try { side = Integer.parseInt(input); if (side <= 0) { // probably a misuse of exceptions throw new NumberFormatException(); } } catch (NumberFormatException numFormExc) { System.out.println("Invalid input. Enter a natural number."); } } while (side <= 0); return side; } I'm interested in two things: Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled. Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is. The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

    Read the article

  • Exceptions confusion

    - by Misiur
    Hi there. I'm trying to build site using OOP in PHP. Everyone is talking about Singleton, hermetization, MVC, and using exceptions. So I've tried to do it like this: Class building whole site: class Core { public $is_core; public $theme; private $db; public $language; private $info; static private $instance; public function __construct($lang = 'eng', $theme = 'default') { if(!self::$instance) { try { $this->db = new sdb(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(PDOException $e) { throw new CoreException($e->getMessage()); } try { $this->language = new Language($lang); } catch(LangException $e) { throw new CoreException($e->getMessage()); } try { $this->theme = new Theme($theme); } catch(ThemeException $e) { throw new CoreException($e->getMessage()); } } return self::$instance; } public function getSite($what) { return $this->language->getLang(); } private function __clone() { } } Class managing themes class Theme { private $theme; public function __construct($name = 'default') { if(!is_dir("themes/$name")) { throw new ThemeException("Unable to load theme $name"); } else { $this->theme = $name; } } public function getTheme() { return $this->theme; } public function display($part) { if(!is_file("themes/$this->theme/$part.php")) { throw new ThemeException("Unable to load theme part: themes/$this->theme/$part.php"); } else { return 'So far so good'; } } } And usage: error_reporting(E_ALL); require_once('config.php'); require_once('functions.php'); try { $core = new Core(); } catch(CoreException $e) { echo 'Core Exception: '.$e->getMessage(); } echo $core->theme->getTheme(); echo "<br />"; echo $core->language->getLang(); try { $core->theme->display('footer'); } catch(ThemeException $e) { echo $e->getMessage(); } I don't like those exception handlers - i don't want to catch them like some pokemons... I want to use things simple: $core-theme-display('footer'); And if something is wrong, and debug mode is enabled, then aplication show error. What should i do?

    Read the article

  • How to create a dynamic Linq Join extension method

    - by Royd Brayshay
    There was a library of dynamic Linq extensions methods released as a sample with VS2008. I'd like to extend it with a Join method. The code below fails with a parameter miss match exception at run time. Can anyone find the problem? public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerSelector, string innerSelector, string resultsSelector, params object[] values) { if (inner == null) throw new ArgumentNullException("inner"); if (outerSelector == null) throw new ArgumentNullException("outerSelector"); if (innerSelector == null) throw new ArgumentNullException("innerSelector"); if (resultsSelector == null) throw new ArgumentNullException("resultsSelctor"); LambdaExpression outerSelectorLambda = DynamicExpression.ParseLambda(outer.ElementType, null, outerSelector, values); LambdaExpression innerSelectorLambda = DynamicExpression.ParseLambda(inner.AsQueryable().ElementType, null, innerSelector, values); ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(outer.ElementType, "outer"), Expression.Parameter(inner.AsQueryable().ElementType, "inner") }; LambdaExpression resultsSelectorLambda = DynamicExpression.ParseLambda(parameters, null, resultsSelector, values); return outer.Provider.CreateQuery( Expression.Call( typeof(Queryable), "Join", new Type[] { outer.ElementType, inner.AsQueryable().ElementType, outerSelectorLambda.Body.Type, innerSelectorLambda.Body.Type, resultsSelectorLambda.Body.Type }, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(resultsSelectorLambda))); } I've now fixed it myself, here's the answer. Please vote it up or add a better one.

    Read the article

  • Parsing concatenated, non-delimited XML messages from TCP-stream using C#

    - by thaller
    I am trying to parse XML messages which are send to my C# application over TCP. Unfortunately, the protocol can not be changed and the XML messages are not delimited and no length prefix is used. Moreover the character encoding is not fixed but each message starts with an XML declaration <?xml>. The question is, how can i read one XML message at a time, using C#. Up to now, I tried to read the data from the TCP stream into a byte array and use it through a MemoryStream. The problem is, the buffer might contain more than one XML messages or the first message may be incomplete. In these cases, I get an exception when trying to parse it with XmlReader.Read or XmlDocument.Load, but unfortunately the XmlException does not really allow me to distinguish the problem (except parsing the localized error string). I tried using XmlReader.Read and count the number of Element and EndElement nodes. That way I know when I am finished reading the first, entire XML message. However, there are several problems. If the buffer does not yet contain the entire message, how can I distinguish the XmlException from an actually invalid, non-well-formed message? In other words, if an exception is thrown before reading the first root EndElement, how can I decide whether to abort the connection with error, or to collect more bytes from the TCP stream? If no exception occurs, the XmlReader is positioned at the start of the root EndElement. Casting the XmlReader to IXmlLineInfo gives me the current LineNumber and LinePosition, however it is not straight forward to get the byte position where the EndElement really ends. In order to do that, I would have to convert the byte array into a string (with the encoding specified in the XML declaration), seek to LineNumber,LinePosition and convert that back to the byte offset. I try to do that with StreamReader.ReadLine, but the stream reader gives no public access to the current byte position. All this seams very inelegant and non robust. I wonder if you have ideas for a better solution. Thank you. EDIT: I looked around and think that the situation is as follows (I might be wrong, corrections are welcome): I found no method so that the XmlReader can continue parsing a second XML message (at least not, if the second message has an XmlDeclaration). XmlTextReader.ResetState could do something similar, but for that I would have to assume the same encoding for all messages. Therefor I could not connect the XmlReader directly to the TcpStream. After closing the XmlReader, the buffer is not positioned at the readers last position. So it is not possible to close the reader and use a new one to continue with the next message. I guess the reason for this is, that the reader could not successfully seek on every possible input stream. When XmlReader throws an exception it can not be determined whether it happened because of an premature EOF or because of a non-wellformed XML. XmlReader.EOF is not set in case of an exception. As workaround I derived my own MemoryBuffer, which returns the very last byte as a single byte. This way I know that the XmlReader was really interested in the last byte and the following exception is likely due to a truncated message (this is kinda sloppy, in that it might not detect every non-wellformed message. However, after appending more bytes to the buffer, sooner or later the error will be detected. I could cast my XmlReader to the IXmlLineInfo interface, which gives access to the LineNumber and the LinePosition of the current node. So after reading the first message I remember these positions and use it to truncate the buffer. Here comes the really sloppy part, because I have to use the character encoding to get the byte position. I am sure you could find test cases for the code below where it breaks (e.g. internal elements with mixed encoding). But up to now it worked for all my tests. The parser class follows here -- may it be useful (I know, its very far from perfect...) class XmlParser { private byte[] buffer = new byte[0]; public int Length { get { return buffer.Length; } } // Append new binary data to the internal data buffer... public XmlParser Append(byte[] buffer2) { if (buffer2 != null && buffer2.Length > 0) { // I know, its not an efficient way to do this. // The EofMemoryStream should handle a List<byte[]> ... byte[] new_buffer = new byte[buffer.Length + buffer2.Length]; buffer.CopyTo(new_buffer, 0); buffer2.CopyTo(new_buffer, buffer.Length); buffer = new_buffer; } return this; } // MemoryStream which returns the last byte of the buffer individually, // so that we know that the buffering XmlReader really locked at the last // byte of the stream. // Moreover there is an EOF marker. private class EofMemoryStream: Stream { public bool EOF { get; private set; } private MemoryStream mem_; public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override bool CanRead { get { return true; } } public override long Length { get { return mem_.Length; } } public override long Position { get { return mem_.Position; } set { throw new NotSupportedException(); } } public override void Flush() { mem_.Flush(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { count = Math.Min(count, Math.Max(1, (int)(Length - Position - 1))); int nread = mem_.Read(buffer, offset, count); if (nread == 0) { EOF = true; } return nread; } public EofMemoryStream(byte[] buffer) { mem_ = new MemoryStream(buffer, false); EOF = false; } protected override void Dispose(bool disposing) { mem_.Dispose(); } } // Parses the first xml message from the stream. // If the first message is not yet complete, it returns null. // If the buffer contains non-wellformed xml, it ~should~ throw an exception. // After reading an xml message, it pops the data from the byte array. public Message deserialize() { if (buffer.Length == 0) { return null; } Message message = null; Encoding encoding = Message.default_encoding; //string xml = encoding.GetString(buffer); using (EofMemoryStream sbuffer = new EofMemoryStream (buffer)) { XmlDocument xmlDocument = null; XmlReaderSettings settings = new XmlReaderSettings(); int LineNumber = -1; int LinePosition = -1; bool truncate_buffer = false; using (XmlReader xmlReader = XmlReader.Create(sbuffer, settings)) { try { // Read to the first node (skipping over some element-types. // Don't use MoveToContent here, because it would skip the // XmlDeclaration too... while (xmlReader.Read() && (xmlReader.NodeType==XmlNodeType.Whitespace || xmlReader.NodeType==XmlNodeType.Comment)) { }; // Check for XML declaration. // If the message has an XmlDeclaration, extract the encoding. switch (xmlReader.NodeType) { case XmlNodeType.XmlDeclaration: while (xmlReader.MoveToNextAttribute()) { if (xmlReader.Name == "encoding") { encoding = Encoding.GetEncoding(xmlReader.Value); } } xmlReader.MoveToContent(); xmlReader.Read(); break; } // Move to the first element. xmlReader.MoveToContent(); // Read the entire document. xmlDocument = new XmlDocument(); xmlDocument.Load(xmlReader.ReadSubtree()); } catch (XmlException e) { // The parsing of the xml failed. If the XmlReader did // not yet look at the last byte, it is assumed that the // XML is invalid and the exception is re-thrown. if (sbuffer.EOF) { return null; } throw e; } { // Try to serialize an internal data structure using XmlSerializer. Type type = null; try { type = Type.GetType("my.namespace." + xmlDocument.DocumentElement.Name); } catch (Exception e) { // No specialized data container for this class found... } if (type == null) { message = new Message(); } else { // TODO: reuse the serializer... System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(type); message = (Message)ser.Deserialize(new XmlNodeReader(xmlDocument)); } message.doc = xmlDocument; } // At this point, the first XML message was sucessfully parsed. // Remember the lineposition of the current end element. IXmlLineInfo xmlLineInfo = xmlReader as IXmlLineInfo; if (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) { LineNumber = xmlLineInfo.LineNumber; LinePosition = xmlLineInfo.LinePosition; } // Try to read the rest of the buffer. // If an exception is thrown, another xml message appears. // This way the xml parser could tell us that the message is finished here. // This would be prefered as truncating the buffer using the line info is sloppy. try { while (xmlReader.Read()) { } } catch { // There comes a second message. Needs workaround for trunkating. truncate_buffer = true; } } if (truncate_buffer) { if (LineNumber < 0) { throw new Exception("LineNumber not given. Cannot truncate xml buffer"); } // Convert the buffer to a string using the encoding found before // (or the default encoding). string s = encoding.GetString(buffer); // Seek to the line. int char_index = 0; while (--LineNumber > 0) { // Recognize \r , \n , \r\n as newlines... char_index = s.IndexOfAny(new char[] {'\r', '\n'}, char_index); // char_index should not be -1 because LineNumber>0, otherwise an RangeException is // thrown, which is appropriate. char_index++; if (s[char_index-1]=='\r' && s.Length>char_index && s[char_index]=='\n') { char_index++; } } char_index += LinePosition - 1; var rgx = new System.Text.RegularExpressions.Regex(xmlDocument.DocumentElement.Name + "[ \r\n\t]*\\>"); System.Text.RegularExpressions.Match match = rgx.Match(s, char_index); if (!match.Success || match.Index != char_index) { throw new Exception("could not find EndElement to truncate the xml buffer."); } char_index += match.Value.Length; // Convert the character offset back to the byte offset (for the given encoding). int line1_boffset = encoding.GetByteCount(s.Substring(0, char_index)); // remove the bytes from the buffer. buffer = buffer.Skip(line1_boffset).ToArray(); } else { buffer = new byte[0]; } } return message; } }

    Read the article

  • Taking "do the simplest thing that could possible work" too far in TDD: testing for a file-name kno

    - by Support - multilanguage SO
    For TDD you have to Create a test that fail Do the simplest thing that could possible work to pass the test Add more variants of the test and repeat Refactor when a pattern emerge With this approach you're supposing to cover all the cases ( that comes to my mind at least) but I'm wonder if am I being too strict here and if it is possible to "think ahead" some scenarios instead of simple discover them. For instance, I'm processing a file and if it doesn't conform to a certain format I am to throw an InvalidFormatException So my first test was: @Test void testFormat(){ // empty doesn't do anything nor throw anything processor.validate("empty.txt"); try { processor.validate("invalid.txt"); assert false: "Should have thrown InvalidFormatException"; } catch( InvalidFormatException ife ) { assert "Invalid format".equals( ife.getMessage() ); } } I run it and it fails because it doesn't throw an exception. So the next thing that comes to my mind is: "Do the simplest thing that could possible work", so I : public void validate( String fileName ) throws InvalidFormatException { if(fileName.equals("invalid.txt") { throw new InvalidFormatException("Invalid format"); } } Doh!! ( although the real code is a bit more complicated, I found my self doing something like this several times ) I know that I have to eventually add another file name and other test that would make this approach impractical and that would force me to refactor to something that makes sense ( which if I understood correctly is the point of TDD, to discover the patterns the usage unveils ) but: Q: am I taking too literal the "Do the simplest thing..." stuff?

    Read the article

  • Worksheet.Unprotect - Office Interop - Difference between 2003 and 2007

    - by sdmcnitt
    I have a .NET winforms app that automates Excel and checks for a worksheet password. The requirements are to be able to detect 1) that the protection is turned off 2) that the password is removed (protected but there is no password) 3) that the password matches the correct password from a database To meet the second requirement the program calls the Worksheet.Unprotect command with a null string, capturing the error. If error as expected, the 3rd check is made. If no error, then the Unprotect worked without a password == password was removed. The code sample below has these checks. The application can do this fine with Office 2003. I have since had my dev machine updated to Office 2007 and it no longer works as it did. When I call the Worksheet.Unprotect, Excel prompts for the password! I need to know how this should be accomplished in the new version of Excel or if there is a way to reference the old PIA. No matter what if I set a reference to Excel 11 it is replaced with the PIA for 12 in the GAC. 'return true if unprotect of worksheet does not generate an error 'all other errors will bubble up 'return false if specific error is "Password is invalid..." Try 'detect unprotected or no password If oWorksheet.ProtectContents Then 'try with no passsword and expect an error 'if no error then raise exception Dim blnRaiseException As Boolean = True Try 'oWorksheet.Unprotect(vbNullString) oWorksheet.Unprotect() Catch ex As Exception blnRaiseException = False End Try If blnRaiseException Then Throw New ExcelSheetNoPasswordException End If oWorksheet.Unprotect(strPwd) 'no error so if we get here -- success fnCheckWorksheetPwd = True 'leave as it was -- this may still cause workbook to think it is changed oWorksheet.Protect(strPwd) Else Throw New ExcelSheetNotProtectedException End If Catch COMex As System.Runtime.InteropServices.COMException 'handle error code -2146827284 If COMex.ErrorCode = -2146827284 Then 'this is the error we're looking for Else Throw End If Catch ex As Exception Throw End Try

    Read the article

  • What is best strategy to handle exceptions & errors in Rails?

    - by Nick Gorbikoff
    Hello. I was wondering if people would share their best practices / strategies on handling exceptions & errors. Now I'm not asking when to throw an exception ( it has been throroughly answered here: SO: When to throw and Exception) . And I'm not using this for my application flow - but there are legitimate exceptions that happen all the time. For example the most popular one would be ActiveRecordNotFound. What would be the best way to handle it? The DRY way? Right now I'm doing a lot of checking within my controller so if Post.find(5) returns Nil - I check for that and throw a flash message. However while this is very granular - it's a bit cumbersome in a sense that I need to check for exceptions like that in every controller, while most of them are essentially the same and have to do with record not found or related records not found - such as either Post.find(5) not found or if you are trying to display comments related to post that doesn't exist, that would throw an exception (something like Post.find(5).comments[0].created_at) I know you can do something like this in ApplicationController and overwrite it later in a particular controller/method to get more granular support, however would that be a proper way to do it? class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordInvalid do |exception| render :action => (exception.record.new_record? ? :new : :edit) end end

    Read the article

  • Multithreaded IOCP Client Issue

    - by Carl
    I am writing a multithreaded client that uses an IO Completion Port. I create and connect the socket that has the WSA_FLAG_OVERLAPPED attribute set. if ((m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { throw std::exception("Failed to create socket."); } if (WSAConnectByName(m_socket, L"server.com", L"80", &localAddressLength, reinterpret_cast<sockaddr*>(&localAddress), &remoteAddressLength, &remoteAddress, NULL, NULL) == FALSE) { throw std::exception("Failed to connect."); } I associate the IO Completion Port with the socket. if ((m_hIOCP = CreateIoCompletionPort(reinterpret_cast<HANDLE>(m_socket), m_hIOCP, NULL, 8)) == NULL) { throw std::exception("Failed to create IOCP object."); } All appears to go well until I try to send some data over the socket. SocketData* socketData = new SocketData; socketData->hEvent = 0; DWORD bytesSent = 0; if (WSASend(m_socket, socketData->SetBuffer(socketData->GenerateLoginRequestHeader()), 1, &bytesSent, NULL, reinterpret_cast<OVERLAPPED*>(socketData), NULL) == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) { throw std::exception("Failed to send data."); } Instead of returning SOCKET_ERROR with the last error set to WSA_IO_PENDING, WSASend returns immediately. I need the IO to pend and for it's completion to be handled in my thread function which is also my worker thread. unsigned int __stdcall MyClass::WorkerThread(void* lpThis) { } I've done this before but I don't know what is going wrong in this case, I'd greatly appreciate any efforts in helping me fix this problem.

    Read the article

  • Why do the overloads of String.Format exist?

    - by GiddyUpHorsey
    I was using Reflector to look at the implementation of String.Format and had always been under the impression that the overloads of String.Format that took 1, 2 & 3 arguments were optimized versions of the method that takes an object array. However, what I found was that internally they create an object array and then call a method that takes an object array. 1 arg public static string Format(string format, object arg0) { if (format == null) { throw new ArgumentNullException("format"); } return Format(null, format, new object[] { arg0 }); } 2 args public static string Format(string format, object arg0, object arg1) { if (format == null) { throw new ArgumentNullException("format"); } return Format(null, format, new object[] { arg0, arg1 }); } 3 args public static string Format(string format, object arg0, object arg1, object arg2) { if (format == null) { throw new ArgumentNullException("format"); } return Format(null, format, new object[] { arg0, arg1, arg2 }); } Object array public static string Format(string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null) ? "format" : "args"); } return Format(null, format, args); } Internally they all end up using the same code and so using the 1, 2 & 3 argument versions are no faster than the object array version. So my question is - why do they exist? When you use the object array version with a comma separated list of values, the compiler automatically converts the arguments into an object array because of the params/ParamArray keyword which is essentially what the 1, 2 & 3 versions do, so they seem redundant. Why did the BCL designers add these overloads?

    Read the article

  • Access generic type parameter at runtime?

    - by Bart van Heukelom
    Event dispatcher interface public interface EventDispatcher { <T> EventListener<T> addEventListener(EventListener<T> l); <T> void removeEventListener(EventListener<T> l); } Implementation public class DefaultEventDispatcher implements EventDispatcher { @SuppressWarnings("unchecked") private Map<Class, Set<EventListener>> listeners = new HashMap<Class, Set<EventListener>>(); public void addSupportedEvent(Class eventType) { listeners.put(eventType, new HashSet<EventListener>()); } @Override public <T> EventListener<T> addEventListener(EventListener<T> l) { Set<EventListener> lsts = listeners.get(T); // ****** error: cannot resolve T if (lsts == null) throw new RuntimeException("Unsupported event type"); if (!lsts.add(l)) throw new RuntimeException("Listener already added"); return l; } @Override public <T> void removeEventListener(EventListener<T> l) { Set<EventListener> lsts = listeners.get(T); // ************* same error if (lsts == null) throw new RuntimeException("Unsupported event type"); if (!lsts.remove(l)) throw new RuntimeException("Listener is not here"); } } Usage EventListener<ShapeAddEvent> l = addEventListener(new EventListener<ShapeAddEvent>() { @Override public void onEvent(ShapeAddEvent event) { // TODO Auto-generated method stub } }); removeEventListener(l); I've marked two errors with a comment above (in the implementation). Is there any way to get runtime access to this information?

    Read the article

  • Creating a custom Configuration

    - by Rob
    I created a customer configuration class Reports. I then created another class called "ReportsCollection". When I try and do the "ConfigurationManager.GetSection()", it doesn't populate my collection variable. Can anyone see any mistakes in my code? Here is the collection class: public class ReportsCollection : ConfigurationElementCollection { public ReportsCollection() { } protected override ConfigurationElement CreateNewElement() { throw new NotImplementedException(); } protected override ConfigurationElement CreateNewElement(string elementName) { return base.CreateNewElement(elementName); } protected override object GetElementKey(ConfigurationElement element) { throw new NotImplementedException(); } public Report this[int index] { get { return (Report)BaseGet(index); } } } Here is the reports class: public class Report : ConfigurationSection { [ConfigurationProperty("reportName", IsRequired = true)] public string ReportName { get { return (string)this["reportName"]; } //set { this["reportName"] = value; } } [ConfigurationProperty("storedProcedures", IsRequired = true)] public StoredProceduresCollection StoredProcedures { get { return (StoredProceduresCollection)this["storedProcedures"]; } } [ConfigurationProperty("parameters", IsRequired = false)] public ParametersCollection Parameters { get { return (ParametersCollection)this["parameters"]; } } [ConfigurationProperty("saveLocation", IsRequired = true)] public string SaveLocation { get { return (string)this["saveLocation"]; } } [ConfigurationProperty("recipients", IsRequired = true)] public RecipientsCollection Recipients { get { return (RecipientsCollection)this["recipients"]; } } } public class StoredProcedure : ConfigurationElement { [ConfigurationProperty("storedProcedureName", IsRequired = true)] public string StoredProcedureName { get { return (string)this["storedProcedureName"]; } } } public class StoredProceduresCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { throw new NotImplementedException(); } protected override ConfigurationElement CreateNewElement(string elementName) { return base.CreateNewElement(elementName); } protected override object GetElementKey(ConfigurationElement element) { throw new NotImplementedException(); } public StoredProcedure this[int index] { get { return (StoredProcedure)base.BaseGet(index); } } } } And here is the very straight-forward code to create the variable: ReportsCollection reportsCollection = (ReportsCollection) System.Configuration.ConfigurationManager.GetSection("ReportGroup");

    Read the article

  • User entered value validation and level of error catching

    - by Terry
    May I ask should the error catching code be placed at the lowest level or at the top as I am not sure what is the best practice? I prefer placing at the bottom, example a, as Example a public static void Main(string[] args) { string operation = args[0]; int value = Convert.ToInt32(args[1]); if (operation == "date") { DoDate(value); } else if (operation == "month") { DoMonth(value); } } public static void DoMonth(int month) { if (month < 1 || month > 12) { throw new Exception(""); } } public static void DoDate(int date) { if (date < 1 || date > 31) { throw new Exception(""); } } or example b public static void Main(string[] args) { string operation = args[0]; int value = Convert.ToInt32(args[1]); if (operation == "date" && (date < 1 || date > 12)) { throw new Exception(""); } else if (operation == "month" && (month < 1 || month > 31)) { throw new Exception(""); } if (operation == "date") { DoDate(value); } else if (operation == "month") { DoMonth(value); } } public static void DoMonth(int month) { } public static void DoDate(int date) { }

    Read the article

  • wrapping user controls in a transaction

    - by Hans Gruber
    I'm working on heavily dynamic and configurable CMS system. Therefore, many pages are composed of a dynamically loaded set of user controls. To enable loose coupling between containers (pages) and children (user controls), all user controls are responsible for their own persistence. Each User Control is wired up to its data/service layer dependencies via IoC. They also implement an IPersistable interface, which allows the container .aspx page to issue a Save command to its children without knowledge of the number or exact nature of these user controls. Note: what follows is only pseudo-code: public class MyUserControl : IPersistable, IValidatable { public void Save() { throw new NotImplementedException(); } public bool IsValid() { throw new NotImplementedException(); } } public partial class MyPage { public void btnSave_Click(object sender, EventArgs e) { foreach (IValidatable control in Controls) { if (!control.IsValid) { throw new Exception("error"); } } foreach (IPersistable control in Controls) { if (!control.Save) { throw new Exception("error"); } } } } I'm thinking of using declarative transactions from the System.EnterpriseService namespace to wrap the btnSave_Click in a transaction in case of an exception, but I'm not sure how this might be achieved or any pitfalls to such an approach.

    Read the article

  • Java Concurrency in practice sample question

    - by andy boot
    I am reading "Java Concurrency in practice" and looking at the example code on page 51. According to the book this piece of code is at risk of of failure if it has not been published properly. Because I like to code examples and break them to prove how they work. I have tried to make it throw an AssertionError but have failed. (Leading me to my previous question) Can anyone post sample code so that an AssertionError is thrown? Rule: Do not modify the Holder class. public class Holder{ private int n; public Holder(int n){ this.n = n; } public void assertSanity(){ if (n != n) { throw new AssertionError("This statement is false"); } } } I have modified the class to make it more fragile but I still can not get an AssertionError thrown. class Holder2{ private int n; private int n2; public Holder2(int n) throws InterruptedException{ this.n = n; Thread.sleep(200); this.n2 = n; } public void assertSanity(){ if (n != n2) { throw new AssertionError("This statement is false"); } } } Is it possible to make either of the above classes throw an AssertionError? Or do we have to accept that they may occasionally do so and we can't write code to prove it?

    Read the article

  • wrapping aspx user controls commands in a transaction

    - by Hans Gruber
    I'm working on heavily dynamic and configurable CMS system. Therefore, many pages are composed of a dynamically loaded set of user controls. To enable loose coupling between containers (pages) and children (user controls), all user controls are responsible for their own persistence. Each User Control is wired up to its data/service layer dependencies via IoC. They also implement an IPersistable interface, which allows the container .aspx page to issue a Save command to its children without knowledge of the number or exact nature of these user controls. Note: what follows is only pseudo-code: public class MyUserControl : IPersistable, IValidatable { public void Save() { throw new NotImplementedException(); } public bool IsValid() { throw new NotImplementedException(); } } public partial class MyPage { public void btnSave_Click(object sender, EventArgs e) { foreach (IValidatable control in Controls) { if (!control.IsValid) { throw new Exception("error"); } } foreach (IPersistable control in Controls) { if (!control.Save) { throw new Exception("error"); } } } } I'm thinking of using declarative transactions from the System.EnterpriseService namespace to wrap the btnSave_Click in a transaction in case of an exception, but I'm not sure how this might be achieved or any pitfalls to such an approach.

    Read the article

  • Very strange Application.ThreadException behaviour.

    - by Brann
    I'm using the Application.ThreadException event to handle and log unexpected exceptions in my winforms application. Now, somewhere in my application, I've got the following code (or rather something equivalent, but this dummy code is enough to reproduce my issue) : try { throw new NullReferenceException("test"); } catch (Exception ex) { throw new Exception("test2", ex); } I'm clearly expecting my Application_ThreadException handler to be passed the "test2" exception, but this is not always the case. Typically, if another thread marshals my code to the UI, my handler receives the "test" exception, exactly as if I hadn't caught "test" at all. Here is a short sample reproducing this behavior. I have omitted the designer's code. static class Program { [STAThread] static void Main() { Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { Console.WriteLine(e.Exception.Message); } } public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click+=new EventHandler(button1_Click); System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThrowEx)); t.Start(); } private void button1_Click(object sender, EventArgs e) { try { throw new NullReferenceException("test"); } catch (Exception ex) { throw new Exception("test2", ex); } } void ThrowEx() { this.BeginInvoke(new EventHandler(button1_Click)); } } The output of this program on my computer is : test ... here I click button1 test2 I've reproduced this on .net 2.0,3.5 and 4.0. Does someone have a logical explanation ?

    Read the article

  • Are C++ exceptions sufficient to implement thread-local storage?

    - by Potatoswatter
    I was commenting on an answer that thread-local storage is nice and recalled another informative discussion about exceptions where I supposed The only special thing about the execution environment within the throw block is that the exception object is referenced by rethrow. Putting two and two together, wouldn't executing an entire thread inside a function-catch-block of its main function imbue it with thread-local storage? It seems to work fine: #include <iostream> #include <pthread.h> using namespace std; struct thlocal { string name; thlocal( string const &n ) : name(n) {} }; thlocal &get_thread() { try { throw; } catch( thlocal &local ) { return local; } } void print_thread() { cerr << get_thread().name << endl; } void *kid( void *local_v ) try { thlocal &local = * static_cast< thlocal * >( local_v ); throw local; } catch( thlocal & ) { print_thread(); return NULL; } int main() try { thlocal local( "main" ); throw local; } catch( thlocal & ) { print_thread(); pthread_t th; thlocal kid_local( "kid" ); pthread_create( &th, NULL, &kid, &kid_local ); pthread_join( th, NULL ); print_thread(); return 0; } Is this novel or well-characterized? Was my initial premise correct? What kind of overhead does get_thread incur in, say, GCC and VC++? It would require throwing only exceptions derived from struct thlocal, but altogether this doesn't feel like an unproductive insomnia-ridden Sunday morning…

    Read the article

  • What is the difference between these two linq implementations?

    - by Mahesh Velaga
    I was going through Jon Skeet's Reimplemnting Linq to Objects series. In the implementation of where article, I found the following snippets, but I don't get what is the advantage that we are gettting by splitting the original method into two. Original Method: // Naive validation - broken! public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) { throw new ArgumentNullException("source"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } foreach (TSource item in source) { if (predicate(item)) { yield return item; } } } Refactored Method: public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) { throw new ArgumentNullException("source"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return WhereImpl(source, predicate); } private static IEnumerable<TSource> WhereImpl<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { foreach (TSource item in source) { if (predicate(item)) { yield return item; } } } Jon says - Its for eager validation and then defferring for the rest of the part. But, I don't get it. Could some one please explain it in a little more detail, whats the difference between these 2 functions and why will the validations be performed in one and not in the other eagerly? Conclusion/Solution: I got confused due to my lack of understanding on which functions are determined to be iterator-generators. I assumed that, it is based on signature of a method like IEnumerable<T>. But, based on the answers, now I get it, a method is an iterator-generator if it uses yield statements.

    Read the article

  • MVC + Is validation attributes enough?

    - by ebb
    My ViewModel has validation attributes that ensure that it wont be empty etc. - Is that enough or should I let my the code contracts I have made be in the ActionResult too? Example: // CreateCaseViewModel.cs public class CreateCaseViewModel { [Required] public string Topic { get; set; } [Required] public string Message { get; set; } } // CaseController.cs [AuthWhere(AuthorizeRole.Developer)] [HttpPost] public ActionResult Create(CreateCaseViewModel model) { if(!ModelState.IsValid) { // TODO: some cool stuff? } if (string.IsNullOrWhiteSpace(model.Message)) { throw new ArgumentException("Message cannot be null or empty", model.Message); } if (string.IsNullOrWhiteSpace(model.Topic)) { throw new ArgumentException("Topic cannot be null or empty", model.Topic); } var success = false; string message; var userId = new Guid(_membershipService.GetUserByUserName(User.Identity.Name).ProviderUserKey.ToString()); if(userId == Guid.Empty) { throw new ArgumentException("UserId cannot be empty"); } Case createCase = _caseService.CreateCase(model.Topic, model.Message); if(createCase == null) { throw new ArgumentException("Case cannot be null"); } if(_caseService.AddCase(createCase, userId)) { message = ControllerResources.CaseCreateFail; } else { success = true; message = ControllerResources.CaseCreateSuccess; } return Json(new { Success = success, Message = message, Partial = RenderPartialViewToString(ListView, GetCases) }); }

    Read the article

  • PHP : If...Else...Query

    - by Rachel
    I am executing this statement under while (($data=fgetcsv($this->fin,5000,";"))!==FALSE) Now what I want in else loop is to throw exception only for data value which did not satisfy the if condition. Right now am displaying the complete row as I am not sure how to throw exception only for data which does not satisfy the value. Code if ((strtotime($data[11]) &&strtotime($data[12])&&strtotime($data[16]))!==FALSE && ctype_digit($data[0]) && ctype_alnum($data[1]) && ctype_digit($data[2]) && ctype_alnum($data[3]) && ctype_alnum($data[4]) && ctype_alnum($data[5]) && ctype_alnum($data[6]) && ctype_alnum($data[7]) && ctype_alnum($data[8]) && $this->_is_valid($data[9]) && ctype_digit($data[10]) && ctype_digit($data[13]) && $this->_is_valid($data[14])) { //Some Logic } else { throw new Exception ("Data {$data[0], $data[1], $data[2], $data[3], $data[4], $data[5], $data[6], $data[7], $data[8], $data[9], $data[10], $data[11], $data[12], $data[13], $data[14], $data[16]} is not in valid format"); } Guidance would be highly appreciated as to how can I throw exception only for data which did not satisfy the if value.

    Read the article

  • Associate two sets of values

    - by PJW
    I have the following code - public static int GetViewLevel(string viewLevelDesc) { try { switch (viewLevelDesc) { case "All": return 0; case "Office": return 10; case "Manager": return 50; default: throw new Exception("Invalid View Level Description"); } } catch (Exception eX) { throw new Exception("Action: GetViewLevel()" + Environment.NewLine + eX.Message); } } public static string GetViewLevelDescription(int viewLevel) { try { switch (viewLevel) { case 0: return "All"; case 10: return "Office"; case 50: return "Manager"; default: throw new Exception("Invalid View Level Description"); } } catch (Exception eX) { throw new Exception("Action: GetViewLevelDescription()" + Environment.NewLine + eX.Message); } } The two static Methods enable me to either get an int ViewLevel from a string ViewLevelDesc or vice versa. I'm sure the way I have done this is far more cumbersome than it needs to be, and I'm looking for some advice how to achieve the same objective but more concisely. The list of int / string pairs will increase significantly. The ones in the above code are just the first three I intend to use.

    Read the article

  • New Features in ASP.NET Web API 2 - Part I

    - by dwahlin
    I’m a big fan of ASP.NET Web API. It provides a quick yet powerful way to build RESTful HTTP services that can easily be consumed by a variety of clients. While it’s simple to get started using, it has a wealth of features such as filters, formatters, and message handlers that can be used to extend it when needed. In this post I’m going to provide a quick walk-through of some of the key new features in version 2. I’ll focus on some two of my favorite features that are related to routing and HTTP responses and cover additional features in a future post.   Attribute Routing Routing has been a core feature of Web API since it’s initial release and something that’s built into new Web API projects out-of-the-box. However, there are a few scenarios where defining routes can be challenging such as nested routes (more on that in a moment) and any situation where a lot of custom routes have to be defined. For this example, let’s assume that you’d like to define the following nested route:   /customers/1/orders   This type of route would select a customer with an Id of 1 and then return all of their orders. Defining this type of route in the standard WebApiConfig class is certainly possible, but it isn’t the easiest thing to do for people who don’t understand routing well. Here’s an example of how the route shown above could be defined:   public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "CustomerOrdersApiGet", routeTemplate: "api/customers/{custID}/orders", defaults: new { custID = 0, controller = "Customers", action = "Orders" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpFormatter()); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   With attribute based routing, defining these types of nested routes is greatly simplified. To get started you first need to make a call to the new MapHttpAttributeRoutes() method in the standard WebApiConfig class (or a custom class that you may have created that defines your routes) as shown next:   public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Allow for attribute based routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } Once attribute based routes are configured, you can apply the Route attribute to one or more controller actions. Here’s an example:   [HttpGet] [Route("customers/{custId:int}/orders")] public List<Order> Orders(int custId) { var orders = _Repository.GetOrders(custId); if (orders == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return orders; }   This example maps the custId route parameter to the custId parameter in the Orders() method and also ensures that the route parameter is typed as an integer. The Orders() method can be called using the following route: /customers/2/orders   While this is extremely easy to use and gets the job done, it doesn’t include the default “api” string on the front of the route that you might be used to seeing. You could add “api” in front of the route and make it “api/customers/{custId:int}/orders” but then you’d have to repeat that across other attribute-based routes as well. To simply this type of task you can add the RoutePrefix attribute above the controller class as shown next so that “api” (or whatever the custom starting point of your route is) is applied to all attribute routes: [RoutePrefix("api")] public class CustomersController : ApiController { [HttpGet] [Route("customers/{custId:int}/orders")] public List<Order> Orders(int custId) { var orders = _Repository.GetOrders(custId); if (orders == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return orders; } }   There’s much more that you can do with attribute-based routing in ASP.NET. Check out the following post by Mike Wasson for more details.   Returning Responses with IHttpActionResult The first version of Web API provided a way to return custom HttpResponseMessage objects which were pretty easy to use overall. However, Web API 2 now wraps some of the functionality available in version 1 to simplify the process even more. A new interface named IHttpActionResult (similar to ActionResult in ASP.NET MVC) has been introduced which can be used as the return type for Web API controller actions. To return a custom response you can use new helper methods exposed through ApiController such as: Ok NotFound Exception Unauthorized BadRequest Conflict Redirect InvalidModelState Here’s an example of how IHttpActionResult and the helper methods can be used to cleanup code. This is the typical way to return a custom HTTP response in version 1:   public HttpResponseMessage Delete(int id) { var status = _Repository.DeleteCustomer(id); if (status) { return new HttpResponseMessage(HttpStatusCode.OK); } else { throw new HttpResponseException(HttpStatusCode.NotFound); } } With version 2 we can replace HttpResponseMessage with IHttpActionResult and simplify the code quite a bit:   public IHttpActionResult Delete(int id) { var status = _Repository.DeleteCustomer(id); if (status) { //return new HttpResponseMessage(HttpStatusCode.OK); return Ok(); } else { //throw new HttpResponseException(HttpStatusCode.NotFound); return NotFound(); } } You can also cleanup post (insert) operations as well using the helper methods. Here’s a version 1 post action:   public HttpResponseMessage Post([FromBody]Customer cust) { var newCust = _Repository.InsertCustomer(cust); if (newCust != null) { var msg = new HttpResponseMessage(HttpStatusCode.Created); msg.Headers.Location = new Uri(Request.RequestUri + newCust.ID.ToString()); return msg; } else { throw new HttpResponseException(HttpStatusCode.Conflict); } } This is what the code looks like in version 2:   public IHttpActionResult Post([FromBody]Customer cust) { var newCust = _Repository.InsertCustomer(cust); if (newCust != null) { return Created<Customer>(Request.RequestUri + newCust.ID.ToString(), newCust); } else { return Conflict(); } } More details on IHttpActionResult and the different helper methods provided by the ApiController base class can be found here. Conclusion Although there are several additional features available in Web API 2 that I could cover (CORS support for example), this post focused on two of my favorites features. If you have .NET 4.5.1 available then I definitely recommend checking the new features out. Additional articles that cover features in ASP.NET Web API 2 can be found here.

    Read the article

  • Exception Handling Differences Between 32/64 Bit

    - by Alois Kraus
    I do quite a bit of debugging .NET applications but from time to time I see things that are impossible (at a first look). I may ask you dear reader what your mental exception handling model is. Exception handling is easy after all right? Lets suppose the following code:         private void F1(object sender, EventArgs e)         {             try             {                 F2();             }             catch (Exception ex)             {                 throw new Exception("even worse Exception");             }           }           private void F2()         {             try             {                 F3();             }             finally             {                 throw new Exception("other exception");             }         }           private void F3()         {             throw new NotImplementedException();         }   What will the call stack look like when you break into the catch(Exception) clause in Windbg (32 and 64 bit on .NET 3.5 SP1)? The mental model I have is that when an exception is thrown the stack frames are unwound until the catch handler can execute. An exception does propagate the call chain upwards.   So when F3 does throw an exception the control flow will resume at the finally handler in F2 which does throw another exception hiding the original one (that is nasty) and then the new Exception will be catched in F1 where the catch handler is executed. So we should see in the catch handler in F1 as call stack only the F1 stack frame right? Well lets try it out in Windbg. For this I created a simple Windows Forms application with one button which does execute the F1 method in its click handler. When you compile the application for 64 bit and the catch handler is reached you will find with the following commands in Windbg   Load sos extension from the same path where mscorwks was loaded in the current process .loadby sos mscorwks   Beak on clr exceptions sxe clr   Continue execution g   Dump mixed call stack container C++  and .NET Stacks interleaved 0:000> !DumpStack OS Thread Id: 0x1d8 (0) Child-SP         RetAddr          Call Site 00000000002c88c0 000007fefa68f0bd KERNELBASE!RaiseException+0x39 00000000002c8990 000007fefac42ed0 mscorwks!RaiseTheExceptionInternalOnly+0x295 00000000002c8a60 000007ff005dd7f4 mscorwks!JIT_Throw+0x130 00000000002c8c10 000007fefa6942e1 WindowsFormsApplication1!WindowsFormsApplication1.Form1.F1(System.Object, System.EventArgs)+0xb4 00000000002c8c60 000007fefa661012 mscorwks!ExceptionTracker::CallHandler+0x145 00000000002c8d60 000007fefa711a72 mscorwks!ExceptionTracker::CallCatchHandler+0x9e 00000000002c8df0 0000000077b055cd mscorwks!ProcessCLRException+0x25e 00000000002c8e90 0000000077ae55f8 ntdll!RtlpExecuteHandlerForUnwind+0xd 00000000002c8ec0 000007fefa637c1a ntdll!RtlUnwindEx+0x539 00000000002c9560 000007fefa711a21 mscorwks!ClrUnwindEx+0x36 00000000002c9a70 0000000077b0554d mscorwks!ProcessCLRException+0x20d 00000000002c9b10 0000000077ae5d1c ntdll!RtlpExecuteHandlerForException+0xd 00000000002c9b40 0000000077b1fe48 ntdll!RtlDispatchException+0x3cb 00000000002ca220 000007fefdaeaa7d ntdll!KiUserExceptionDispatcher+0x2e 00000000002ca7e0 000007fefa68f0bd KERNELBASE!RaiseException+0x39 00000000002ca8b0 000007fefac42ed0 mscorwks!RaiseTheExceptionInternalOnly+0x295 00000000002ca980 000007ff005dd8df mscorwks!JIT_Throw+0x130 00000000002cab30 000007fefa6942e1 WindowsFormsApplication1!WindowsFormsApplication1.Form1.F2()+0x9f 00000000002cab80 000007fefa71b5b3 mscorwks!ExceptionTracker::CallHandler+0x145 00000000002cac80 000007fefa70dcd0 mscorwks!ExceptionTracker::ProcessManagedCallFrame+0x683 00000000002caed0 000007fefa7119af mscorwks!ExceptionTracker::ProcessOSExceptionNotification+0x430 00000000002cbd90 0000000077b055cd mscorwks!ProcessCLRException+0x19b 00000000002cbe30 0000000077ae55f8 ntdll!RtlpExecuteHandlerForUnwind+0xd 00000000002cbe60 000007fefa637c1a ntdll!RtlUnwindEx+0x539 00000000002cc500 000007fefa711a21 mscorwks!ClrUnwindEx+0x36 00000000002cca10 0000000077b0554d mscorwks!ProcessCLRException+0x20d 00000000002ccab0 0000000077ae5d1c ntdll!RtlpExecuteHandlerForException+0xd 00000000002ccae0 0000000077b1fe48 ntdll!RtlDispatchException+0x3cb 00000000002cd1c0 000007fefdaeaa7d ntdll!KiUserExceptionDispatcher+0x2e 00000000002cd780 000007fefa68f0bd KERNELBASE!RaiseException+0x39 00000000002cd850 000007fefac42ed0 mscorwks!RaiseTheExceptionInternalOnly+0x295 00000000002cd920 000007ff005dd968 mscorwks!JIT_Throw+0x130 00000000002cdad0 000007ff005dd875 WindowsFormsApplication1!WindowsFormsApplication1.Form1.F3()+0x48 00000000002cdb10 000007ff005dd786 WindowsFormsApplication1!WindowsFormsApplication1.Form1.F2()+0x35 00000000002cdb60 000007ff005dbe6a WindowsFormsApplication1!WindowsFormsApplication1.Form1.F1(System.Object, System.EventArgs)+0x46 00000000002cdbc0 000007ff005dd452 System_Windows_Forms!System.Windows.Forms.Control.OnClick(System.EventArgs)+0x5a   Hm okaaay. I see my method F1 two times in this call stack. Looks like we did get some recursion bug. But that can´t be given the obvious code above. Let´s try the same thing in a 32 bit process.  0:000> !DumpStack OS Thread Id: 0x33e4 (0) Current frame: KERNELBASE!RaiseException+0x58 ChildEBP RetAddr  Caller,Callee 0028ed38 767db727 KERNELBASE!RaiseException+0x58, calling ntdll!RtlRaiseException 0028ed4c 68b9008c mscorwks!Binder::RawGetClass+0x20, calling mscorwks!Module::LookupTypeDef 0028ed5c 68b904ff mscorwks!Binder::IsClass+0x23, calling mscorwks!Binder::RawGetClass 0028ed68 68bfb96f mscorwks!Binder::IsException+0x14, calling mscorwks!Binder::IsClass 0028ed78 68bfb996 mscorwks!IsExceptionOfType+0x23, calling mscorwks!Binder::IsException 0028ed80 68bfbb1c mscorwks!RaiseTheExceptionInternalOnly+0x2a8, calling KERNEL32!RaiseExceptionStub 0028eda8 68ba0713 mscorwks!Module::ResolveStringRef+0xe0, calling mscorwks!BaseDomain::GetStringObjRefPtrFromUnicodeString 0028edc8 68b91e8d mscorwks!SetObjectReferenceUnchecked+0x19 0028ede0 68c8e910 mscorwks!JIT_Throw+0xfc, calling mscorwks!RaiseTheExceptionInternalOnly 0028ee44 68c8e734 mscorwks!JIT_StrCns+0x22, calling mscorwks!LazyMachStateCaptureState 0028ee54 68c8e865 mscorwks!JIT_Throw+0x1e, calling mscorwks!LazyMachStateCaptureState 0028eea4 02ffaecd (MethodDesc 0x7af08c +0x7d WindowsFormsApplication1.Form1.F1(System.Object, System.EventArgs)), calling mscorwks!JIT_Throw 0028eeec 02ffaf19 (MethodDesc 0x7af098 +0x29 WindowsFormsApplication1.Form1.F2()), calling 06370634 0028ef58 02ffae37 (MethodDesc 0x7a7bb0 +0x4f System.Windows.Forms.Control.OnClick(System.EventArgs))   That does look more familar. The call stack has been unwound and we do see only some frames into the history where the debugger was smart enough to find out that we have called F2 from F1. The exception handling on 64 bit systems does work quite differently which seems to have the nice property to remember the called methods not only during the first pass of exception filter clauses (during first pass all catch handler are called if they are going to catch the exception which is about to be thrown)  but also when the actual stack unwind has taken place. This makes it possible to follow not only the call stack right at the moment but also to look into the “history” of the catch/finally clauses. In a 64 bit process you only need to look at the ExceptionTracker to find out if a catch or finally handler was called. The two frames ProcessManagedCallFrame/CallHandler does indicate a finally clause whereas CallCatchHandler/CallHandler indicates a catch clause. That was a interesting one. Oh and by the way if you manage to load the Microsoft symbols you can also find out the hidden exception which. When you encounter in the call stack a line 0016eb34 75b79617 KERNELBASE!RaiseException+0x58 ====> Exception Code e0434f4d cxr@16e850 exr@16e838 Then it is a good idea to execute .exr 16e838 !analyze –v to find out more. In the managed world it is even easier since we can dump the objects allocated on the stack which have not yet been garbage collected to look at former method parameters. The command !dso which is the abbreviation for dump stack objects will give you 0:000> !dso OS Thread Id: 0x46c (0) ESP/REG  Object   Name 0016dd4c 020737f0 System.Exception 0016dd98 020737f0 System.Exception 0016dda8 01f5c6cc System.Windows.Forms.Button 0016ddac 01f5d2b8 System.EventHandler 0016ddb0 02071744 System.Windows.Forms.MouseEventArgs 0016ddc0 01f5d2b8 System.EventHandler 0016ddcc 01f5c6cc System.Windows.Forms.Button 0016dddc 020737f0 System.Exception 0016dde4 01f5d2b8 System.EventHandler 0016ddec 02071744 System.Windows.Forms.MouseEventArgs 0016de40 020737f0 System.Exception 0016de80 02071744 System.Windows.Forms.MouseEventArgs 0016de8c 01f5d2b8 System.EventHandler 0016de90 01f5c6cc System.Windows.Forms.Button 0016df10 02073784 System.SByte[] 0016df5c 02073684 System.NotImplementedException 0016e2a0 02073684 System.NotImplementedException 0016e2e8 01ed69f4 System.Resources.ResourceManager From there it is easy to do 0:000> !pe 02073684 Exception object: 02073684 Exception type: System.NotImplementedException Message: Die Methode oder der Vorgang sind nicht implementiert. InnerException: <none> StackTrace (generated):     SP       IP       Function     0016ECB0 006904AD WindowsFormsApplication2!WindowsFormsApplication2.Form1.F3()+0x35     0016ECC0 00690411 WindowsFormsApplication2!WindowsFormsApplication2.Form1.F2()+0x29     0016ECF0 0069038F WindowsFormsApplication2!WindowsFormsApplication2.Form1.F1(System.Object, System.EventArgs)+0x3f StackTraceString: <none> HResult: 80004001 to see the former exception. That´s all for today.

    Read the article

  • Code Contracts: Unit testing contracted code

    - by DigiMortal
    Code contracts and unit tests are not replacements for each other. They both have different purpose and different nature. It does not matter if you are using code contracts or not – you still have to write tests for your code. In this posting I will show you how to unit test code with contracts. In my previous posting about code contracts I showed how to avoid ContractExceptions that are defined in code contracts runtime and that are not accessible for us in design time. This was one step further to make my randomizer testable. In this posting I will complete the mission. Problems with current code This is my current code. public class Randomizer {     public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           var rnd = new Random();         return rnd.Next(min, max);     } } As you can see this code has some problems: randomizer class is static and cannot be instantiated. We cannot move this class between components if we need to, GetRandomFromRangeContracted() is not fully testable because we cannot currently affect random number generator output and therefore we cannot test post-contract. Now let’s solve these problems. Making randomizer testable As a first thing I made Randomizer to be class that must be instantiated. This is simple thing to do. Now let’s solve the problem with Random class. To make Randomizer testable I define IRandomGenerator interface and RandomGenerator class. The public constructor of Randomizer accepts IRandomGenerator as argument. public interface IRandomGenerator {     int Next(int min, int max); }   public class RandomGenerator : IRandomGenerator {     private Random _random = new Random();       public int Next(int min, int max)     {         return _random.Next(min, max);     } } And here is our Randomizer after total make-over. public class Randomizer {     private IRandomGenerator _generator;       private Randomizer()     {         _generator = new RandomGenerator();     }       public Randomizer(IRandomGenerator generator)     {         _generator = generator;     }       public int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return _generator.Next(min, max);     } } It seems to be inconvenient to instantiate Randomizer now but you can always use DI/IoC containers and break compiled dependencies between the components of your system. Writing tests for randomizer IRandomGenerator solved problem with testing post-condition. Now it is time to write tests for Randomizer class. Writing tests for contracted code is not easy. The main problem is still ContractException that we are not able to access. Still it is the main exception we get as soon as contracts fail. Although pre-conditions are able to throw exceptions with type we want we cannot do much when post-conditions will fail. We have to use Contract.ContractFailed event and this event is called for every contract failure. This way we find ourselves in situation where supporting well input interface makes it impossible to support output interface well and vice versa. ContractFailed is nasty hack and it works pretty weird way. Although documentation sais that ContractFailed is good choice for testing contracts it is still pretty painful. As a last chance I got tests working almost normally when I wrapped them up. Can you remember similar solution from the times of Visual Studio 2008 unit tests? Cannot understand how Microsoft was able to mess up testing again. [TestClass] public class RandomizerTest {     private Mock<IRandomGenerator> _randomMock;     private Randomizer _randomizer;     private string _lastContractError;       public TestContext TestContext { get; set; }       public RandomizerTest()     {         Contract.ContractFailed += (sender, e) =>         {             e.SetHandled();             e.SetUnwind();               throw new Exception(e.FailureKind + ": " + e.Message);         };     }       [TestInitialize()]     public void RandomizerTestInitialize()     {         _randomMock = new Mock<IRandomGenerator>();         _randomizer = new Randomizer(_randomMock.Object);         _lastContractError = string.Empty;     }       #region InputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_not_less_than_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(100, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_equal_to_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(10, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     public void GetRandomFromRangeContracted_should_work_when_min_is_less_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 50;           _randomMock.Setup(r => r.Next(minValue, maxValue))             .Returns(returnValue)             .Verifiable();           var result = _randomizer.GetRandomFromRangeContracted(minValue, maxValue);           _randomMock.Verify();         Assert.AreEqual<int>(returnValue, result);     }     #endregion       #region OutputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_less_than_min()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 7;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_more_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 102;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }     #endregion        } Although these tests are pretty awful and contain hacks we are at least able now to make sure that our code works as expected. Here is the test list after running these tests. Conclusion Code contracts are very new stuff in Visual Studio world and as young technology it has some problems – like all other new bits and bytes in the world. As you saw then making our contracted code testable is easy only to the point when pre-conditions are considered. When we start dealing with post-conditions we will end up with hacked tests. I hope that future versions of code contracts will solve error handling issues the way that testing of contracted code will be easier than it is right now.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >