Search Results

Search found 525 results on 21 pages for 'readability'.

Page 15/21 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Fair Comments

    - by Tony Davis
    To what extent is good code self-documenting? In one of the most entertaining sessions I saw at the recent PASS summit, Jeremiah Peschka (blog | twitter) got a laugh out of a sleepy post-lunch audience with the following remark: "Some developers say good code is self-documenting; I say, get off my team" I silently applauded the sentiment. It's not that all comments are useful, but that I mistrust the basic premise that "my code is so clearly written, it doesn't need any comments". I've read many pieces describing the road to self-documenting code, and my problem with most of them is that they feed the myth that comments in code are a sign of weakness. They aren't; in fact, used correctly I'd say they are essential. Regardless of how far intelligent naming can get you in describing what the code does, or how well any accompanying unit tests can explain to your fellow developers why it works that way, it's no excuse not to document fully the public interfaces to your code. Maybe I just mixed with the wrong crowd while learning my favorite language, but when I open a stored procedure I lose the will even to read it unless I see a big Phil Factor- or Jeff Moden-style header summarizing in plain English what the code does, how it fits in to the broader application, and a usage example. This public interface describes the high-level process and should explain the role of the code, clearly, for fellow developers, language non-experts, and even any non-technical stake holders in the project. When you step into the body of the code, the low-level details, then I agree that the rules are somewhat different; especially when code is subject to frequent refactoring that can quickly render comments redundant or misleading. At their worst, here, inline comments are sticking plaster to cover up the scars caused by poor naming conventions, failure in clarity when mapping a complex domain into code, or just by not entirely understanding the problem (/ this is the clever part). If you design and refactor your code carefully so that it is as simple as possible, your functions do one thing only, you avoid having two completely different algorithms in the same piece of code, and your functions, classes and variables are intelligently named, then, yes, the need for inline comments should be minimal. And yet, even given this, I'd still argue that many languages (T-SQL certainly being one) just don't lend themselves to readability when performing even moderately-complex tasks. If the algorithm is complex, I still like to see the occasional helpful comment. Please, therefore, be as liberal as you see fit in the detail of the comments you apply to this editorial, for like code it is bound to increase its' clarity and usefulness. Cheers, Tony.

    Read the article

  • Ad-hoc taxonomy: owning the chess set doesn't mean you decide how the little horsey moves

    - by Roger Hart
    There was one of those little laugh-or-cry moments recently when I heard an anecdote about content strategy failings at a major online retailer. The story goes a bit like this: successful company in a highly commoditized marketplace succeeds on price and largely ignores its content team. Being relatively entrepreneurial, the founders are still knocking around, and occasionally like to "take an interest". One day, they decree that clothing sold on the site can no longer be described as "unisex", because this sounds old fashioned. Sad now. Let me just reiterate for the folks at the back: large retailer, commoditized market place, differentiating on price. That's inherently unstable. Sooner or later, they're going to need one or both of competitive differentiation and significant optimization. I can't speak for the latter, since I'm hypothesizing off a raft of rumour, but one of the simpler paths to the former is to become - or rather acknowledge that they are - a content business. Regardless, they need highly-searchable terminology. Even in the face of tooth and claw resistance to noticing the fundamental position content occupies in driving sales (and SEO) on the web, there's a clear information problem here. Dilettante taxonomy is a disaster. Ok, so this is a small example, but that kind of makes it a good one. Unisex probably is the best way of describing clothing designed to suit either men or women interchangeably. It certainly takes less time to type (and read). It's established terminology, and as a single word, it's significantly better for web readability than a phrasal workaround. Something like "fits men or women" is short, by could fall foul of clause-level discard in web scanning. It's not an adjective, so for intuitive reading it's never going to be near the start of a title or description. It would also clutter up search results, and impose cognitive load in list scanning. Sorry kids, it's just worse. Even if "unisex" were an archaism (which it isn't), the only thing that would weigh against its being more usable and concise terminology would be evidence that this archaism were hurting conversions. Good luck with that. We once - briefly - called one of our products a "Can of worms". It was a bundle in a bug-tracking suite, and we thought it sounded terribly cool. Guess how well that sold. We have information and content professionals for a reason: to make sure that whatever we put in front of users is optimised to meet user and business goals. If that thinking doesn't inform style guides, taxonomy, messaging, title structure, and so forth, you might as well be finger painting.

    Read the article

  • Code refactoring with Visual Studio 2010-Part 3

    - by Jalpesh P. Vadgama
    I have been writing few post about Code refactoring features of visual studio 2010 and This blog post is also one of them. In this post I am going to show you reorder parameters features in visual studio 2010. As a developer you might need to reorder parameter of a method or procedure in code for better readability of the the code and if you do this task manually then it is tedious job to do. But Visual Studio Reorder Parameter code refactoring feature can do this stuff within a minute. So let’s see how its works. For this I have created a simple console application which I have used earlier posts . Following is a code for that. using System; namespace CodeRefractoring { class Program { static void Main(string[] args) { string firstName = "Jalpesh"; string lastName = "Vadgama"; PrintMyName(firstName, lastName); } private static void PrintMyName(string firstName, string lastName) { Console.WriteLine(string.Format("FirstName:{0}", firstName)); Console.WriteLine(string.Format("LastName:{0}", lastName)); Console.ReadLine(); } } } Above code is very simple. It just print a firstname and lastname via PrintMyName method. Now I want to reorder the firstname and lastname parameter of PrintMyName. So for that first I have to select method and then click Refactor Menu-> Reorder parameters like following. Once you click a dialog box appears like following where it will give options to move parameter with arrow navigation like following. Now I am moving lastname parameter as first parameter like following. Once you click OK it will show a preview option where I can see the effects of changes like following. Once I clicked Apply my code will be changed like following. using System; namespace CodeRefractoring { class Program { static void Main(string[] args) { string firstName = "Jalpesh"; string lastName = "Vadgama"; PrintMyName(lastName, firstName); } private static void PrintMyName(string lastName, string firstName) { Console.WriteLine(string.Format("FirstName:{0}", firstName)); Console.WriteLine(string.Format("LastName:{0}", lastName)); Console.ReadLine(); } } } As you can see its very easy to use this feature. Hoped you liked it.. Stay tuned for more.. Till that happy programming.

    Read the article

  • Au revoir, Python?

    - by GuySmiley
    I'm an ex-C++ programmer who's recently discovered (and fallen head-over-heels with) Python. I've taken some time to become reasonably fluent in Python, but I've encountered some troubling realities that may lead me to drop it as my language of choice, at least for the time being. I'm writing this in the hopes that someone out there can talk me out of it by convincing me that my concerns are easily circumvented within the bounds of the python universe. I picked up python while looking for a single flexible language that will allow me to build end-to-end working systems quickly on a variety of platforms. These include: - web services - mobile apps - cross-platform client apps for PC Development speed is more of a priority at the time-being than execution speed. However, in order to improve performance over time without requiring major re-writes or architectural changes I think it's imperative to be able to interface easily with Java. That way, I can use Java to optimize specific components as the application scales, without throwing away any code. As far as I can tell, my requirement for an enterprise-capable, platform-independent, fast language with a large developer base means it would have to be Java. .NET or C++ would not cut it due to their respective limitations. Also Java is clearly de rigeur for most mobile platforms. Unfortunately, tragically, there doesn't seem to be a good way to meet all these demands. Jython seems to be what I'm looking for in principle, except that it appears to be practically dead, with no one developing, supporting, or using it to any great degree. And also Jython seems too married to the Java libraries, as you can't use many of the CPython standard libraries with it, which has a major impact on the code you end up writing. The only other option that I can see is to use JPype wrapped in marshalling classes, which may work although it seems like a pain and I wonder if it would be worth it in the long run. On the other hand, everything I'm looking for seems to be readily available by using JRuby, which seems to be much better supported. As things stand, I think this is my best option. I'm sad about this because I absolutely love everything about Python, including the syntax. The perl-like constructs in Ruby just feel like such a step backwards to me in terms of readability, but at the end of the day most of the benefits of python are available in Ruby as well. So I ask you - am I missing something here? Much of what I've said is based on what I've read, so is this summary of the current landscape accurate, or is there some magical solution to the Python-Java divide that will snuff these concerns and allow me to comfortably stay in my happy Python place?

    Read the article

  • Exciting product releases (and one disappointing thing) with Mix10

    - by Jeff
    Sadly, I'm not at Mix this year, for the first time in a few years. It's a little harder to go if you work for Microsoft, oddly enough. And then there's this little guy next to me, who at ten days old really needs his daddy to be around! But oh, the excitement of what Microsoft has in store! It's great to finally see all of these major releases coming together for Microsoft developer products. There is a great deal of excitement among people internally no matter where you work, because there is so much cool stuff in the pipe. In case you live under a rock...Visual Studio 2010 - Great to see all of the positive feedback on the Twitter and what not. I've been using it on one of my home products for awhile, and I really like it. The newer nightly builds of ReSharper also seem to be gaining speed in quality as well. I like the new debugging features, and the text readability is not imagined. Love it.Silverlight 4 - I've been running a couple of minor SL3 apps on my personal sites for awhile now, and I'm thrilled with the platform. With a couple of key concepts down, .NET folk like you and me can do some stellar things with this, and if you're a Mac nerd (like me), it's all kinds of awesome to be able to build stuff for it without the agony of Objective-C and X Code.Windows Phone 7 Series - A few weeks ago you got to see the shiny new UI that went beyond the icon grid, and now you've got the developer story as well. That I can adapt my existing Silverlight apps with minimal effort to work on the phone is pretty powerful. Millions of .NET devs just because phone developers, using the tools they already know. How great is that?ASP.NET MVC2 - The final bits shipped last week, and there was much rejoicing. I love this framework because of the testability and the real ability to get to the true mechanics of HTTP. The other cool thing is the speed at which the framework has evolved. v2 in less than a year is pretty "un-Microsoft" in a lot of eyes.The video of keynotes and sessions is starting to appear on the Mix site, but for reasons I can't understand, they're WMV downloads. For real? Not that helpful for Mac folk. Why wouldn't they be using a Silverlight player?In any case, the thing that continues to motivate me is that getting what you imagine on to the Internet gets easier every year. This is not a new revelation for me. I've only been at Microsoft for four months, but I've felt this way for years. I'm thrilled to be a part of it.

    Read the article

  • How To Build An Enterprise Application - Introduction

    - by Tuan Nguyen
    An enterprise application is a software which fulfills 4 core quality attributes: Reliability Flexibility Reusability Maintainability Reliability is the ability of a system or component to perform its required functions under stated conditions for a specific period of time. Because there are no ways more than testing to make sure a system is reliability, we can exchange the term reliability with the term testability. Flexibility is the ability of changing a system's core features without violating unrelated features or components. Although flexibility can helps us to achieve interoperability easily but the opposite is not true. For example, a program might run on multiple platforms, contains logic for many scenarios but that wouldn't mean it was flexibility if it forces us rewrite code in all components when we just want to change some aspects of a feature it had. Reusability is the ability of sharing one or more system's components for another system. We should just open a component's reusability in the context in which it is used. For example, we write classes that implement UI logic and deliver them to only classes which implementing UI. Maintainability is the ability of adding or removing features to a system after it was released. Maintainability consists of many factors such as readability, analyzability, extensibility therein extensibility is critical. Maintainability requires us to write code that is longer and complexer than normal but it doesn't mean we introduce unneccessarily complex code. We always try to make our code clear and transparent to everyone. An application enterprise is built on an enterprise design which consists of two parts: low-level design and high-level design. At low-level design, it focuses on building loose-coupled classes or components. Particularly, it recommends: Each class or component undertakes only single responsibility (design based on unit test) Classes or components implement and work through interfaces (design based on contract) Dependency relationship between classes and components could be injected at run-time (design based on dependency) At high-level design, it focuses on architecting system into tiers and layers. Particularly, it recommends: Divide system into subsystems for deployment. Each subsytem is called a tier. Typical, an enterprise application would have 3 tiers as illustrated in the following figure: Arrange classes and components to logical containers called layers. Typical, an enterprise application would have 5 layers as illustrated in the following figure

    Read the article

  • How to convince my boss that quality is a good thing to have in code?

    - by Kristof Claes
    My boss came to me today to ask me if we could implement a certain feature in 1.5 days. I had a look at it and told him that 2 to 3 days would be more realistic. He then asked me: "And what if we do it quick and dirty?" I asked him to explain what he meant with "quick and dirty". It turns out, he wants us to write code as quickly as humanly possible by (for example) copying bits and pieces from other projects, putting all code in the code-behind of the WebForms pages, stop caring about DRY and SOLID and assuming that the code and functionalities will never ever have to be modified or changed. What's even worse, he doesn't want us do it for just this one feature, but for all the code we write. We can make more profit when we do things quick and dirty. Clients don't want to pay for you taking into account that something might change in the future. The profits for us are in delivering code as quick as possible. As long as the application does what it needs to do, the quality of the code doesn't matter. They never see the code. I have tried to convince him that this is a bad way to think as the manager of a software company, but he just wouldn't listen to my arguments: Developer motivation: I explained that it is hard to keep developers motivated when they are constantly under pressure of unrealistic deadlines and budget to write sloppy code very quickly. Readability: When a project gets passed on to another developer, cleaner and better structured code will be easier to read and understand. Maintainability: It is easier, safer and less time consuming to adapt, extend or change well written code. Testability: It is usually easier to test and find bugs in clean code. My co-workers are as baffled as I am by my boss' standpoint, but we can't seem to get to him. He keeps on saying that by making things more quickly, we can sell more projects, ask a lower price for them while still making a bigger profit. And in the end these projects pay the developer's salaries. What more can I say to make him see he is wrong? I want to buy him copies of Peopleware and The Mythical Man-Month, but I have a feeling they won't change his mind either. A lot of you will probably say something like "Run! Get out of there now!" or "I'd quit!", but that's not really an option since .NET web development jobs are rather rare in the region where I live...

    Read the article

  • Commit Review Questions

    - by Wes McClure
    Note: in this article when I refer to a commit, I mean the commit you plan to share with the rest of the team, if you have local commits that you plan to amend/combine, I am referring to the final result. In time you will find these easier to do as you develop, however, all of these are valuable before checking in!  The pre commit review is a nice time to polish what might have been several hours of intense work, during which these things were the last things on your mind!  If you are concerned about losing your work in the process of responding to these questions, first do a check-in and amend it as you go (assuming you are using a tool such as git that supports this), rolling the result into one nice commit for everyone else.  Did you review your commit, change by change, with a diff utility? If not, this is a list of reasons why you might want to start! Did you test your changes? If the test is valuable to be automated, is it? If it’s a manual testing scenario, did you at least try the basics manually? Are the additions/changes formatted consistently with the rest of the project? Lots of automated tools can help here, don’t try to manually format the code, that’s a waste of time and as a human you will fail repeatedly. Are these consistent: tabs versus spaces, indentation, spacing, braces, line breaks, etc Resharper is a great example of a tool that can automate this for you (.net) Are naming conventions respected? Did you accidently use abbreviations, unless you have a good reason to use them? Does capitalization match the conventions in the project/language? Are files partitioned? Sometimes we add new code in existing files in a pinch, it’s a good idea to split these out if they don’t belong ie: are new classes defined in new files, if this is something your project values? Is there commented out code? If you are removing an existing feature, get rid of it, that is why we have VCS If it’s not done yet, then why are you checking it in? Perhaps a stash commit (git)? Did you leave debug or unnecessary changes? Do you understand all of the changes? http://geekswithblogs.net/wesm/archive/2012/04/11/programming-doesnrsquot-have-to-be-magic.aspx Are there spelling mistakes? Including your commit message! Is your commit message concise? Is there follow up work? Are there tasks you didn’t write down that you need to follow up with? Are readability or reorganization changes needed? This might be amended into the final commit, or it might be future work that needs added to the backlog. Are there other things your team values that you should review?

    Read the article

  • Your interesting code tricks/ conventions? [closed]

    - by Paul
    What interesting conventions, rules, tricks do you use in your code? Preferably some that are not so popular so that the rest of us would find them as novelties. :) Here's some of mine... Input and output parameters This applies to C++ and other languages that have both references and pointers. This is the convention: input parameters are always passed by value or const reference; output parameters are always passed by pointer. This way I'm able to see at a glance, directly from the function call, what parameters might get modified by the function: Inspiration: Old C code int a = 6, b = 7, sum = 0; calculateSum(a, b, &sum); Ordering of headers My typical source file begins like this (see code below). The reason I put the matching header first is because, in case that header is not self-sufficient (I forgot to include some necessary library, or forgot to forward declare some type or function), a compiler error will occur. // Matching header #include "example.h" // Standard libraries #include <string> ... Setter functions Sometimes I find that I need to set multiple properties of an object all at once (like when I just constructed it and I need to initialize it). To reduce the amount of typing and, in some cases, improve readability, I decided to make my setters chainable: Inspiration: Builder pattern class Employee { public: Employee& name(const std::string& name); Employee& salary(double salary); private: std::string name_; double salary_; }; Employee bob; bob.name("William Smith").salary(500.00); Maybe in this particular case it could have been just as well done in the constructor. But for Real WorldTM applications, classes would have lots more fields that should be set to appropriate values and it becomes unmaintainable to do it in the constructor. So what about you? What personal tips and tricks would you like to share?

    Read the article

  • Base Pages and Interfaces for ASP.NET Pages

    - by geekrutherford
    For quite a while I have been using the concept of base pages when developing pages in ASP.NET applications. It is a wonderful method for exposing common functions to all of your applications pages and also overriding certain events for various purposes (i.e. dynamic themes).  Recently I found out a new developer will be joining my team. This prompted me to review the applications code for readability and ease of maintenance. I began adding comments through out the code behind for all pages within the application. While doing so I noted that I had used common method names for such things as loading data, configuring controls, applying filters, etc.   Bringing a new developer on board, I wanted to make the transition as seamless as possible while also ensuring they follow existing coding practices we already have in place. While I could have created virtual methods for the common page methods allowing them to overridden, what I really needed was a way to ensure the new developer implemented the same methods for each and every page. Thus I created an interface to force the issue.   Now, every page not only inherits the base page class but also implements an interface. This provides every page not only common functions and overridden page events but also imposes rules for implementing certain common methods :-)   Interface   public interface BasePageInterface { /// Configures page based on users security permissions. void CheckPermissions(); /// Configures Filter Form control for current page.  /// Ensure you have set the FilteredGrid and PageAjaxManager properties of the FilterForm control in PageLoad!!!  void ConfigureFilters(); /// Sets event handlers and default settings for controls on the current page. void ConfigureControls(); /// Exports data bound to grid in selected format. void ExportGridData(ExportFormat fmt); /// Loads data and binds to grid. /// Columns are turned on/off in grid depending on tab selected and users permissions.  void LoadData(); }   Page code-behind class definition:   public partial class MyPage : BasePage, BasePageInterface Note, you could not use an abstract class to accomplish this considering C# does not allow for multiple inheritance.  Nor could the base page class be abstract since it needs to inherit from the System.Web.UI.Page class in order to override page events.

    Read the article

  • Wireframing: A Day In the Life of UX Workshop at Oracle

    - by ultan o'broin
    The Oracle Applications User Experience team's Day in the Life (DITL) of User Experience (UX) event was run in Oracle's Redwood Shores HQ for Oracle Usability Advisory Board (OUAB) members. I was charged with putting together a wireframing session, together with Director of Financial Applications User Experience, Scott Robinson (@scottrobinson). Example of stunning new wireframing visuals we used on the DITL events. We put on a lively show, explaining the basics of wireframing, the concepts, what it is and isn't, considerations on wireframing tool choice, and then imparting some tips and best practices. But the real energy came when the OUAB customers and partners in the room were challenge to do some wireframing of their own. Wireframing is about bringing your business and product use cases to life in real UX visual terms, by creating a low-fidelity drawing to iterate and agree on in advance of prototyping and coding what is to be finally built and rolled out for users. All the best people wireframe. Leonardo da Vinci used "cartoons" on some great works, tracing outlines first and using red ochre or charcoal dropped through holes in the tracing parchment onto the canvas to outline the subject. (Image distributed under Wikimedia commons license) Wireframing an application's user experience design enables you to: Obtain stakeholder buy-in. Enable faster iteration of different designs. Determine the task flow navigation paths (in Oracle Fusion Applications navigation is linked with user roles). Develop a content strategy (readability, search engine optimization (SEO) of content, and so on) Lay out the pages, widgets, groups of features, and so on. Apply usability heuristics early (no replacement for usability testing, but a great way to do some heavy-lifting up front). Decide upstream which functional user experience design patterns to apply (out of the box solutions that expedite productivity). Assess which Oracle Application Development Framework (ADF) or equivalent technology components can be used (again, developer productivity is enhanced downstream). We ran a lively hands-on exercise where teams wireframed a choice of application scenarios using the time-honored tools of pen and paper. Scott worked the floor like a pro, pointing out great use of features, best practices, innovations, and making sure that the whole concept of wireframing, the gestalt, transferred. "We need more buttons!" The cry of the energized. Not quite. The winning wireframe session (online shopping scenario) from the Applications UX DITL event shown. Great fun, great energy, and great teamwork were evident in the room. Naturally, there were prizes for the best wireframe. Well, actually, prizes were handed out to the other attendees too! An exciting, slightly different aspect to delivery of this session made the wireframing event one of the highlights of the day. And definitely, something we will repeat again when we get the chance. Thanks to everyone who attended, contributed, and helped organize.

    Read the article

  • When to use typedef?

    - by futlib
    I'm a bit confused about if and when I should use typedef in C++. I feel it's a balancing act between readability and clarity. Here's a code sample without any typedefs: int sum(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last) { static std::map<std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>, int> lookup_table; std::map<std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>, int>::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } Pretty ugly IMO. So I'll add some typedefs within the function to make it look nicer: int sum(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last) { typedef std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator> Lookup_key; typedef std::map<Lookup_key, int> Lookup_table; static Lookup_table lookup_table; Lookup_table::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } The code is still a bit clumsy, but I get rid of most nightmare material. But there's still the int vector iterators, this variant gets rid of those: typedef std::vector<int>::const_iterator Input_iterator; int sum(Input_iterator first, Input_iterator last) { typedef std::tuple<Input_iterator, Input_iterator> Lookup_key; typedef std::map<Lookup_key, int> Lookup_table; static Lookup_table lookup_table; Lookup_table::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } This looks clean, but is it still readable? When should I use a typedef? As soon as I have a nightmare type? As soon as it occurs more than once? Where should I put them? Should I use them in function signatures or keep them to the implementation?

    Read the article

  • Separate Action from Assertion in Unit Tests

    - by DigitalMoss
    Setup Many years ago I took to a style of unit testing that I have come to like a lot. In short, it uses a base class to separate out the Arrangement, Action and Assertion of the test into separate method calls. You do this by defining method calls in [Setup]/[TestInitialize] that will be called before each test run. [Setup] public void Setup() { before_each(); //arrangement because(); //action } This base class usually includes the [TearDown] call as well for when you are using this setup for Integration tests. [TearDown] public void Cleanup() { after_each(); } This often breaks out into a structure where the test classes inherit from a series of Given classes that put together the setup (i.e. GivenFoo : GivenBar : WhenDoingBazz) with the Assertions being one line tests with a descriptive name of what they are covering [Test] public void ThenBuzzSouldBeTrue() { Assert.IsTrue(result.Buzz); } The Problem There are very few tests that wrap around a single action so you end up with lots of classes so recently I have taken to defining the action in a series of methods within the test class itself: [Test] public void ThenBuzzSouldBeTrue() { because_an_action_was_taken(); Assert.IsTrue(result.Buzz); } private void because_an_action_was_taken() { //perform action here } This results in several "action" methods within the test class but allows grouping of similar tests (i.e. class == WhenTestingDifferentWaysToSetBuzz) The Question Does someone else have a better way of separating out the three 'A's of testing? Readability of tests is important to me so I would prefer that, when a test fails, that the very naming structure of the tests communicate what has failed. If someone can read the Inheritance structure of the tests and have a good idea why the test might be failing then I feel it adds a lot of value to the tests (i.e. GivenClient : GivenUser : WhenModifyingUserPermissions : ThenReadAccessShouldBeTrue). I am aware of Acceptance Testing but this is more on a Unit (or series of units) level with boundary layers mocked. EDIT : My question is asking if there is an event or other method for executing a block of code before individual tests (something that could be applied to specific sets of tests without it being applied to all tests within a class like [Setup] currently does. Barring the existence of this event, which I am fairly certain doesn't exist, is there another method for accomplishing the same thing? Using [Setup] for every case presents a problem either way you go. Something like [Action("Category")] (a setup method that applied to specific tests within the class) would be nice but I can't find any way of doing this.

    Read the article

  • A solution for a PHP website without a framework

    - by lortabac
    One of our customers asked us to add some dynamic functionality to an existent website, made of several static HTML pages. We normally work with an MVC framework (mostly CodeIgniter), but in this case moving everything to a framework would require too much time. Since it is not a big project, not having the full functionality of a framework is not a problem. But the question is how to keep code clean. The solution I came up with is to divide code in libraries (the application's API) and models. So inside HTML there will only be API calls, and readability will not be sacrificed. I implemented this with a sort of static Registry (sorry if I'm wrong, I am not a design pattern expert): <?php class Custom_framework { //Global database instance private static $db; //Registered models private static $models = array(); //Registered libraries private static $libraries = array(); //Returns a database class instance static public function get_db(){ if(isset(self::$db)){ //If instance exists, returns it return self::$db; } else { //If instance doesn't exists, creates it self::$db = new DB; return self::$db; } } //Returns a model instance static public function get_model($model_name){ if(isset(self::$models[$model_name])){ //If instance exists, returns it return self::$models[$model_name]; } else { //If instance doesn't exists, creates it if(is_file(ROOT_DIR . 'application/models/' . $model_name . '.php')){ include_once ROOT_DIR . 'application/models/' . $model_name . '.php'; self::$models[$model_name] = new $model_name; return self::$models[$model_name]; } else { return FALSE; } } } //Returns a library instance static public function get_library($library_name){ if(isset(self::$libraries[$library_name])){ //If instance exists, returns it return self::$libraries[$library_name]; } else { //If instance doesn't exists, creates it if(is_file(ROOT_DIR . 'application/libraries/' . $library_name . '.php')){ include_once ROOT_DIR . 'application/libraries/' . $library_name . '.php'; self::$libraries[$library_name] = new $library_name; return self::$libraries[$library_name]; } else { return FALSE; } } } } Inside HTML, API methods are accessed like this: <?php echo Custom_framework::get_library('My_library')->my_method(); ?> It looks to me as a practical solution. But I wonder what its drawbacks are, and what the possible alternatives.

    Read the article

  • Adding JavaScript to your code dependent upon conditions

    - by DavidMadden
    You might be in an environment where you code is source controlled and where you might have build options to different environments.  I recently encountered this where the same code, built on different configurations, would have the website at a different URL.  If you are working with ASP.NET as I am you will have to do something a bit crazy but worth while.  If someone has a more efficient solution please share. Here is what I came up with to make sure the client side script was placed into the HEAD element for the Google Analytics script.  GA wants to be the last in the HEAD element so if you are doing others in the Page_Load then you should do theirs last. The settings object below is an instance of a class that holds information I collection.  You could read from different sources depending on where you stored your unique ID for Google Analytics. *** This has been formatted to fit this screen. *** if (!IsPostBack) { if (settings.GoogleAnalyticsID != null || settings.GoogleAnalyticsID != string.Empty) { string str = @"//<!CDATA[ var _gaq = _gaq || []; _gaq.push(['_setAccount', '"  + settings.GoogleAnalyticsID + "']); _gaq.push(['_trackPageview']);  (function () {  var ga = document.createElement('script');  ga.type = 'text/javascript';  ga.async = true;  ga.src = ('https:' == document.location.protocol  ? 'https://ssl' :  'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0];  s.parentNode.insertBefore(ga, s);})();"; System.Web.UI.HtmlControls.HtmlGenericControl si =  new System.Web.UI.HtmlControls.HtmlGenericControl(); si.TagName = "script"; si.Attributes.Add("type", @"text/javascript"); si.InnerHtml = sb.ToString(); this.Page.Header.Controls.Add(si); } } The code above will prevent the code from executing if it is a PostBack and then if the ID was not able to be read or something caused the settings to be lost by accident. If you have larger function to declare, you can use a StringBuilder to separate the lines. This is the most compact I wished to go and manage readability.

    Read the article

  • Enum types, FlagsAttribute & Zero value – Part 2

    - by nmgomes
    In my previous post I wrote about why you should pay attention when using enum value Zero. After reading that post you are probably thinking like Benjamin Roux: Why don’t you start the enum values at 0x1? Well I could, but doing that I lose the ability to have Sync and Async mutually exclusive by design. Take a look at the following enum types: [Flags] public enum OperationMode1 { Async = 0x1, Sync = 0x2, Parent = 0x4 } [Flags] public enum OperationMode2 { Async = 0x0, Sync = 0x1, Parent = 0x2 } To achieve mutually exclusion between Sync and Async values using OperationMode1 you would have to operate both values: protected void CheckMainOperarionMode(OperationMode1 mode) { switch (mode) { case (OperationMode1.Async | OperationMode1.Sync | OperationMode1.Parent): case (OperationMode1.Async | OperationMode1.Sync): throw new InvalidOperationException("Cannot be Sync and Async simultaneous"); break; case (OperationMode1.Async | OperationMode1.Parent): case (OperationMode1.Async): break; case (OperationMode1.Sync | OperationMode1.Parent): case (OperationMode1.Sync): break; default: throw new InvalidOperationException("No default mode specified"); } } but this is a by design constraint in OperationMode2. Why? Simply because 0x0 is the neutral element for the bitwise OR operation. Knowing this singularity, replacing and simplifying the previous method, you get: protected void CheckMainOperarionMode(OperationMode2 mode) { switch (mode) { case (OperationMode2.Sync | OperationMode2.Parent): case (OperationMode2.Sync): break; case (OperationMode2.Parent): default: break; } This means that: if both Sync and Async values are specified Sync value always win (Zero is the neutral element for bitwise OR operation) if no Sync value specified, the Async method is used. Here is the final method implementation: protected void CheckMainOperarionMode(OperationMode2 mode) { if (mode & OperationMode2.Sync == OperationMode2.Sync) { } else { } } All content above prove that Async value (0x0) is useless from the arithmetic perspective, but, without it we lose readability. The following IF statements are logically equals but the first is definitely more readable: if (OperationMode2.Async | OperationMode2.Parent) { } if (OperationMode2.Parent) { } Here’s another example where you can see the benefits of 0x0 value, the default value can be used explicitly. <my:Control runat="server" Mode="Async,Parent"> <my:Control runat="server" Mode="Parent">

    Read the article

  • Loopback connection via PHP's getimage size crashes server (Magento's CMS)

    - by Alex
    We were able to trace down a problem that is crashing our NGINX server running Magento until the following point: Background info: Magento Backend has a CMS function with a WYSIWYG editor. This editor loads some pictures via a controller in magento (cms/directive). When we set the NGINX error_log level to info, we get the following lines (line break inserted for better readability): 2012/10/22 18:05:40 [info] 14105#0: *1 client closed prematurely connection, so upstream connection is closed too while sending request to upstream, client: XXXXXXXXX, server: test.local, request: "GET index.php/admin/cms_wysiwyg/directive/___directive/BASEENCODEDIMAGEURL,,/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9024", host: "test.local" When checking the code in the debugger, the following call does never return (in ´Varien_Image_Adapter_Abstract::getMimeType()` # $this->_fileName is http://test.local/skin/adminhtml/base/default/images/demo-image-not-existing.gif` # $_SERVER['REQUEST_URI'] = http://test.local/admin/cms_wysiwyg/directive/___directive/BASEENCODEDIMAGEURL list($this->_imageSrcWidth, $this->_imageSrcHeight, $this->_fileType, ) = getimagesize($this->_fileName); The filename requests is an URL to the same server which is requesting the script a link to a static .gif that is not existing. Sample URL: http://test.local/skin/adminhtml/base/default/images/demo-image-not-existing.gif When the above line executed, any subsequent request to the NGNIX server does not respond any more. After waiting for around 10 minutes, the NGINX server starts answering requests again. I tried to reproduce the error with a simple test script that only calls getimagesize() with the given URL - but this not crash. It simple leads to an exception saying that the URL could not be loaded (which is fine as the URL is wrong)

    Read the article

  • MySQL select query result set changes based on column order

    - by user197191
    I have a drupal 7 site using the Views module to back-end site content search results. The same query with the same dataset returns different results from MySQL 5.5.28 to MySQL 5.6.14. The results from 5.5.28 are the correct, expected results. The results from 5.6.14 are not. If, however, I simply move a column in the select statement, the query returns the correct results. Here is the code-generated query in question (modified for readability). I apologize for the length; I couldn't find a way to reproduce it without the whole query: SELECT DISTINCT node_node_revision.nid AS node_node_revision_nid, node_revision.title AS node_revision_title, node_field_revision_field_position_institution_ref.nid AS node_field_revision_field_position_institution_ref_nid, node_revision.vid AS vid, node_revision.nid AS node_revision_nid, node_node_revision.title AS node_node_revision_title, SUM(search_index.score * search_total.count) AS score, 'node' AS field_data_field_system_inst_name_node_entity_type, 'node' AS field_revision_field_position_college_division_node_entity_t, 'node' AS field_revision_field_position_department_node_entity_type, 'node' AS field_revision_field_search_lvl_degree_lvls_node_entity_type, 'node' AS field_revision_field_position_app_deadline_node_entity_type, 'node' AS field_revision_field_position_start_date_node_entity_type, 'node' AS field_revision_body_node_entity_type FROM node_revision node_revision LEFT JOIN node node_node_revision ON node_revision.nid = node_node_revision.nid LEFT JOIN field_revision_field_position_institution_ref field_revision_field_position_institution_ref ON node_revision.vid = field_revision_field_position_institution_ref.revision_id AND (field_revision_field_position_institution_ref.entity_type = 'node' AND field_revision_field_position_institution_ref.deleted = '0') LEFT JOIN node node_field_revision_field_position_institution_ref ON field_revision_field_position_institution_ref.field_position_institution_ref_target_id = node_field_revision_field_position_institution_ref.nid LEFT JOIN field_revision_field_position_cip_code field_revision_field_position_cip_code ON node_revision.vid = field_revision_field_position_cip_code.revision_id AND (field_revision_field_position_cip_code.entity_type = 'node' AND field_revision_field_position_cip_code.deleted = '0') LEFT JOIN node node_field_revision_field_position_cip_code ON field_revision_field_position_cip_code.field_position_cip_code_target_id = node_field_revision_field_position_cip_code.nid LEFT JOIN node node_node_revision_1 ON node_revision.nid = node_node_revision_1.nid LEFT JOIN field_revision_field_position_vacancy_status field_revision_field_position_vacancy_status ON node_revision.vid = field_revision_field_position_vacancy_status.revision_id AND (field_revision_field_position_vacancy_status.entity_type = 'node' AND field_revision_field_position_vacancy_status.deleted = '0') LEFT JOIN search_index search_index ON node_revision.nid = search_index.sid LEFT JOIN search_total search_total ON search_index.word = search_total.word WHERE ( ( (node_node_revision.status = '1') AND (node_node_revision.type IN ('position')) AND (field_revision_field_position_vacancy_status.field_position_vacancy_status_target_id IN ('38')) AND( (search_index.type = 'node') AND( (search_index.word = 'accountant') ) ) AND ( (node_revision.vid=node_node_revision.vid AND node_node_revision.status=1) ) ) ) GROUP BY search_index.sid, vid, score, field_data_field_system_inst_name_node_entity_type, field_revision_field_position_college_division_node_entity_t, field_revision_field_position_department_node_entity_type, field_revision_field_search_lvl_degree_lvls_node_entity_type, field_revision_field_position_app_deadline_node_entity_type, field_revision_field_position_start_date_node_entity_type, field_revision_body_node_entity_type HAVING ( ( (COUNT(*) >= '1') ) ) ORDER BY node_node_revision_title ASC LIMIT 20 OFFSET 0; Again, this query returns different sets of results from MySQL 5.5.28 (correct) to 5.6.14 (incorrect). If I move the column named "score" (the SUM() column) to the end of the column list, the query returns the correct set of results in both versions of MySQL. My question is: Is this expected behavior (and why), or is this a bug? I'm on the verge of reverting my entire environment back to 5.5 because of this.

    Read the article

  • MRTG Monitoring of Disk

    - by Antitribu
    I am trying to monitor Disk usage over SNMP using MRTG on CentOS5.2. I'm open to any suggestions as to the best way to achieve this (I would also like to do other metrics like CPU). Please don't assume I know anything about MRTG. I am using the following config: LoadMIBs: /usr/share/snmp/mibs/UCD-SNMP-MIB.txt,/usr/share/snmp/mibs/TCP-MIB.txt workdir: /var/www/html/mrtg/temp/ # # Disk Usage Monitoring # Target[servername.]: dskPercent.0&dskPercent.0:[email protected] Title[servername.]: / on servername routers.cgi*Desc[servername.]: / on servername routers.cgi*ShortDesc[servername.]: / MaxBytes[servername.]: 100 AbsMax[servername.]: 100 Options[servername.]: growright,nopercent,gauge YLegend[servername.]: used disk space ShortLegend[servername.]: % used Legend1[servername.]: usage Legend2[servername.]: usage Legend3[servername.]: peak usage Legend4[servername.]: peak usage LegendI[servername.]: usage LegendO[servername.]: usage routers.cgi*Icon[servername.]: disk-sm.gif routers.cgi*Options[servername.]: noo,nomax,noabsmax Unscaled[servername.]: dwmy I receive the errors: Unknown SNMP var dskPercent.0 at /usr/bin/mrtg line 2035 Unknown SNMP var dskPercent.0 at /usr/bin/mrtg line 2035 From forum surfing etc the suggestion is to use the fully qualified OIDs, I'd like to avoid this (for readability). So essentially I'm wondering where can I find a mib file compatible with mrtg for it's reference or a working config file.

    Read the article

  • Nginx: Loopback connection via PHP's getimage size crashes server (Magento's CMS)

    - by Alex
    We were able to trace down a problem that is crashing our NGINX server running Magento until the following point: Background info: Magento Backend has a CMS function with a WYSIWYG editor. This editor loads some pictures via a controller in magento (cms/directive). When we set the NGINX error_log level to info, we get the following lines (line break inserted for better readability): 2012/10/22 18:05:40 [info] 14105#0: *1 client closed prematurely connection, so upstream connection is closed too while sending request to upstream, client: XXXXXXXXX, server: test.local, request: "GET index.php/admin/cms_wysiwyg/directive/___directive/BASEENCODEDIMAGEURL,,/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9024", host: "test.local" When checking the code in the debugger, the following call does never return (in ´Varien_Image_Adapter_Abstract::getMimeType()` # $this->_fileName is http://test.local/skin/adminhtml/base/default/images/demo-image-not-existing.gif` # $_SERVER['REQUEST_URI'] = http://test.local/admin/cms_wysiwyg/directive/___directive/BASEENCODEDIMAGEURL list($this->_imageSrcWidth, $this->_imageSrcHeight, $this->_fileType, ) = getimagesize($this->_fileName); The filename requests is an URL to the same server which is requesting the script a link to a static .gif that is not existing. Sample URL: http://test.local/skin/adminhtml/base/default/images/demo-image-not-existing.gif When the above line executed, any subsequent request to the NGNIX server does not respond any more. After waiting for around 10 minutes, the NGINX server starts answering requests again. I tried to reproduce the error with a simple test script that only calls getimagesize() with the given URL - but this not crash. It simple leads to an exception saying that the URL could not be loaded (which is fine as the URL is wrong)

    Read the article

  • How to automatically start VM created by virt-manager?

    - by Jeff Shattock
    I have created a virtual machine with virt-manager that runs on kvm/qemu. The machine works well when started through virt-manager. However, I would like to be able to start and stop the VM through a script in init.d, so that it comes up and down along with the host. I need to have virt-manager show that the machine is running, and to be able to connect to its console through there. When I use the command line that is produced by running ps -eaf | grep kvm after starting the vm through virt-manager, I get some console messages about redirected character devices, but the machine does start and runs properly. However, I do not get any indication from virt-manager that it has started. How can I modify the command line to get virt-manager to pick up the running VM? Is there anything else about the command line that should change when starting outside of virt-manager? Command line is (slightly reformatted for readability): /usr/bin/kvm -S -M pc-0.12 -enable-kvm -m 512 -smp 1 -name BORON \ -uuid fa7e5fbd-7d8e-43c4-ebd9-1504a4383eb1 \ -chardev socket,id=monitor,path=/var/lib/libvirt/qemu/BORON.monitor,server,nowait \ -monitor chardev:monitor -localtime -boot c \ -drive file=/dev/FS1/BORON,if=ide,index=0,boot=on,format=raw \ -net nic,macaddr=52:54:00:20:0b:fd,vlan=0,name=nic.0 \ -net tap,fd=41,vlan=0,name=tap.0 -chardev pty,id=serial0 -serial chardev:serial0 \ -parallel none -usb -usbdevice tablet -vnc 127.0.0.1:1 -k en-us -vga cirrus

    Read the article

  • How to continue an HTTrack mirroring session from the command line?

    - by isme
    I want to drive my mirroring project using the Command Prompt instead of the WinHTTrack interface so that I can script and schedule the mirroring session more easily. The output of httrack --help gives a simple command for continuing an interrupted mirroring session: example: httrack --continue continues a mirror in the current folder When I try httrack --continue in my HTTrack project folder, all I get is output like this: Example: -%F "<!-- Mirrored from %s by HTTrack Website Copier/3.x [XR&CO'2010], %s -->" * Option %F needs to be followed by a blank space, and a footer string With each parameter on a new line for readability, the first line of my doit.log file looks like this: -qiC1%P0s0b0u1j0%s%u0N0%I0p1DaK0c1T30H0%kf2E1800A25000%c0.1%f#f -F "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" -%F "" -%l "en, en, *" http://saa.gov.uk/search.php?SEARCHED=1&SEARCH_TABLE=council_tax&SEARCH_TERM=City+of+Edinburgh&DISPLAY_COUNT=100 -O1 "C:\\Users\\Iain\\Projects\\Council Tax Analysis\\Code\\HTTrack\\Council Tax Valuation List" -* \ +*search.php?SEARCHED=1* -*DISPLAY_MODE=FULL* The parameter %F "" should tell HTTrack to use an empty footer. I used the WinHTTrack interface to create the project and start the mirroring session. I can interrupt and continue the mirroring session using the interface. The HTML files saved by WinHTTrack have no footer.

    Read the article

  • LinkBuilder.BuildUrlFromExpression not working anymore in .Net 4 / VS 2010 ?

    - by Mose
    Hi, I recently migrating my ASP.Net MVC 1 application from VS.Net 2008 / C# 3.5 to VS.NET 2010 / C# 4.0. I massively used a builder to get URL strings from the strongly typed calls. It looks like this : // sample call : string toSamplePage = Url.To<SampleController>(c => c.Page(parameter1, parameter2)); the code is added as an extension to the default UrlHelper : public static string To<Tcontroller>(UrlHelper helper, Expression<Action<Tcontroller>> action) where Tcontroller : Controller { // based on Microsoft.Web.Mvc.dll LinkBuilder return LinkBuilder.BuildUrlFromExpression<Tcontroller>(helper.RequestContext, helper.RouteCollection, action); } The only problem of this, is the reference to Microsoft.Web.Mvc dll, but the gain in readability was worth it. Problem : it does not work anymore, return (null) whatever the parameters. Questions : is there a better way now to build links from an expression ? (yes I tried to google it without success) is there a trick to have the former LinkBuilder.BuildUrlFromExpression works ? I tried to recompile it into C# 4.0, but the problem is that it implies working on my own compilated version of System.Web.Mvc which is not an option. I'm currently trying to migrate to MVC 2 but I still have issues... Waiting for your suggestions...

    Read the article

  • Split WPF Style XAML Files

    - by anon
    Most WPF styles I have seen are split up into one very long Theme.xaml file. I want to split mine up for readability so my Theme.xaml looks like this: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;v3.0.0.0;31bf3856ad364e35;component/themes/aero.normalcolor.xaml"/> <ResourceDictionary Source="Controls/Brushes.xaml"/> <ResourceDictionary Source="Controls/Buttons.xaml"/> ... </ResourceDictionary.MergedDictionaries> </ResourceDictionary> The problem is that this solution does not work. I have a default button style which is BasedOn the default Aero style for a button: <Style x:Key="{x:Type Button}" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="FontSize" Value="14"/> ... </Style> If I place all of this in one file it works but as soon as I split it up I get StackOverflow exceptions because it thinks it is BasedOn itself. Is there a way around this? How does WPF add resources when merging resource dictionaries?

    Read the article

  • F# Powerpack's Metadata doesn't recognize FSharp.Core as an F# library

    - by Nathan Sanders
    Here's my test code to isolate the problem: open Microsoft.FSharp.Metadata [<EntryPoint>] let main args = let core = FSharpAssembly.FromFile @"C:\Program Files\FSharp-2.0.0.0\\bin\FSharp.Core.dll" let core2 = FSharpAssembly.FSharpLibrary let core3 = System.AppDomain.CurrentDomain.GetAssemblies() |> Seq.find (fun a -> a.FullName.Contains "Core") |> FSharpAssembly.FromAssembly core.Entities |> Seq.iter (printfn "%A") 0 All three lets should give me the same FSharpAssembly. Instead, all 3 throw an exception that FSharp.Core is not an F# assembly (details below, re-formatted for readability). Two more clues: Using the core3 method, I get the same error for the test F# assembly itself I don't get the error at FSI after doing #r "@C:\Program Files...\FSharp.Powerpack.Metadata.dll". Any ideas? I'm using Visual Studio 2008, F# 2.0 and F# Powerpack 2.0.0.0 (May 20, 2010) release on an oldish XP VM, I think it's updated to SP3 though. (I got the error this morning with Powerpack 1.9.9.9, so I upgraded to 2.0.0.0. I thought that if 1.9.9.9 doesn't recognise F#'s 2.0.0.0's assemblies, then maybe bugfixes in Powerpack 2.0.0.0 would help.) Unhandled Exception: System.TypeInitializationException: The type initializer for 'Microsoft.FSharp.Metadata.AssemblyLoader' threw an exception. ---> System.TypeInitializationException: The type initializer for '<StartupCode$FSharp-PowerPack-Metadata>.$Metadata' threw an exception. ---> System.ArgumentException: could not produce an FSharpAssembly object for the assembly 'FSharp.Core' because this is not an F# assembly Parameter name: name at Microsoft.FSharp.Metadata.AssemblyLoader.Add(String name,Assembly assembly) at <StartupCode$FSharp-PowerPack-Metadata>.$Metadata..cctor() --- End of inner exception stack trace --- at Microsoft.FSharp.Metadata.AssemblyLoader..cctor() --- End of inner exception stack trace --- at Microsoft.FSharp.Metadata.AssemblyLoader.Get(Assembly assembly) at Microsoft.FSharp.Metadata.FSharpAssembly.FromAssembly(Assembly assembly) at Program.main(String[] args) in C:\Documents an...\FSMetadataTest\Program.fs:line 11 Press any key to continue . . .

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21  | Next Page >