Search Results

Search found 47 results on 2 pages for 'moles'.

Page 1/2 | 1 2  | Next Page >

  • Mocking the Unmockable: Using Microsoft Moles with Gallio

    - by Thomas Weller
    Usual opensource mocking frameworks (like e.g. Moq or Rhino.Mocks) can mock only interfaces and virtual methods. In contrary to that, Microsoft’s Moles framework can ‘mock’ virtually anything, in that it uses runtime instrumentation to inject callbacks in the method MSIL bodies of the moled methods. Therefore, it is possible to detour any .NET method, including non-virtual/static methods in sealed types. This can be extremely helpful when dealing e.g. with code that calls into the .NET framework, some third-party or legacy stuff etc… Some useful collected resources (links to website, documentation material and some videos) can be found in my toolbox on Delicious under this link: http://delicious.com/thomasweller/toolbox+moles A Gallio extension for Moles Originally, Moles is a part of Microsoft’s Pex framework and thus integrates best with Visual Studio Unit Tests (MSTest). However, the Moles sample download contains some additional assemblies to also support other unit test frameworks. They provide a Moled attribute to ease the usage of mole types with the respective framework (there are extensions for NUnit, xUnit.net and MbUnit v2 included with the samples). As there is no such extension for the Gallio platform, I did the few required lines myself – the resulting Gallio.Moles.dll is included with the sample download. With this little assembly in place, it is possible to use Moles with Gallio like that: [Test, Moled] public void SomeTest() {     ... What you can do with it Moles can be very helpful, if you need to ‘mock’ something other than a virtual or interface-implementing method. This might be the case when dealing with some third-party component, legacy code, or if you want to ‘mock’ the .NET framework itself. Generally, you need to announce each moled type that you want to use in a test with the MoledType attribute on assembly level. For example: [assembly: MoledType(typeof(System.IO.File))] Below are some typical use cases for Moles. For a more detailed overview (incl. naming conventions and an instruction on how to create the required moles assemblies), please refer to the reference material above.  Detouring the .NET framework Imagine that you want to test a method similar to the one below, which internally calls some framework method:   public void ReadFileContent(string fileName) {     this.FileContent = System.IO.File.ReadAllText(fileName); } Using a mole, you would replace the call to the File.ReadAllText(string) method with a runtime delegate like so: [Test, Moled] [Description("This 'mocks' the System.IO.File class with a custom delegate.")] public void ReadFileContentWithMoles() {     // arrange ('mock' the FileSystem with a delegate)     System.IO.Moles.MFile.ReadAllTextString = (fname => fname == FileName ? FileContent : "WrongFileName");       // act     var testTarget = new TestTarget.TestTarget();     testTarget.ReadFileContent(FileName);       // assert     Assert.AreEqual(FileContent, testTarget.FileContent); } Detouring static methods and/or classes A static method like the below… public static string StaticMethod(int x, int y) {     return string.Format("{0}{1}", x, y); } … can be ‘mocked’ with the following: [Test, Moled] public void StaticMethodWithMoles() {     MStaticClass.StaticMethodInt32Int32 = ((x, y) => "uups");       var result = StaticClass.StaticMethod(1, 2);       Assert.AreEqual("uups", result); } Detouring constructors You can do this delegate thing even with a class’ constructor. The syntax for this is not all  too intuitive, because you have to setup the internal state of the mole, but generally it works like a charm. For example, to replace this c’tor… public class ClassWithCtor {     public int Value { get; private set; }       public ClassWithCtor(int someValue)     {         this.Value = someValue;     } } … you would do the following: [Test, Moled] public void ConstructorTestWithMoles() {     MClassWithCtor.ConstructorInt32 =            ((@class, @value) => new MClassWithCtor(@class) {ValueGet = () => 99});       var classWithCtor = new ClassWithCtor(3);       Assert.AreEqual(99, classWithCtor.Value); } Detouring abstract base classes You can also use this approach to ‘mock’ abstract base classes of a class that you call in your test. Assumed that you have something like that: public abstract class AbstractBaseClass {     public virtual string SaySomething()     {         return "Hello from base.";     } }      public class ChildClass : AbstractBaseClass {     public override string SaySomething()     {         return string.Format(             "Hello from child. Base says: '{0}'",             base.SaySomething());     } } Then you would set up the child’s underlying base class like this: [Test, Moled] public void AbstractBaseClassTestWithMoles() {     ChildClass child = new ChildClass();     new MAbstractBaseClass(child)         {                 SaySomething = () => "Leave me alone!"         }         .InstanceBehavior = MoleBehaviors.Fallthrough;       var hello = child.SaySomething();       Assert.AreEqual("Hello from child. Base says: 'Leave me alone!'", hello); } Setting the moles behavior to a value of  MoleBehaviors.Fallthrough causes the ‘original’ method to be called if a respective delegate is not provided explicitly – here it causes the ChildClass’ override of the SaySomething() method to be called. There are some more possible scenarios, where the Moles framework could be of much help (e.g. it’s also possible to detour interface implementations like IEnumerable<T> and such…). One other possibility that comes to my mind (because I’m currently dealing with that), is to replace calls from repository classes to the ADO.NET Entity Framework O/R mapper with delegates to isolate the repository classes from the underlying database, which otherwise would not be possible… Usage Since Moles relies on runtime instrumentation, mole types must be run under the Pex profiler. This only works from inside Visual Studio if you write your tests with MSTest (Visual Studio Unit Test). While other unit test frameworks generally can be used with Moles, they require the respective tests to be run via command line, executed through the moles.runner.exe tool. A typical test execution would be similar to this: moles.runner.exe <mytests.dll> /runner:<myframework.console.exe> /args:/<myargs> So, the moled test can be run through tools like NCover or a scripting tool like MSBuild (which makes them easy to run in a Continuous Integration environment), but they are somewhat unhandy to run in the usual TDD workflow (which I described in some detail here). To make this a bit more fluent, I wrote a ReSharper live template to generate the respective command line for the test (it is also included in the sample download – moled_cmd.xml). - This is just a quick-and-dirty ‘solution’. Maybe it makes sense to write an extra Gallio adapter plugin (similar to the many others that are already provided) and include it with the Gallio download package, if  there’s sufficient demand for it. As of now, the only way to run tests with the Moles framework from within Visual Studio is by using them with MSTest. From the command line, anything with a managed console runner can be used (provided that the appropriate extension is in place)… A typical Gallio/Moles command line (as generated by the mentioned R#-template) looks like that: "%ProgramFiles%\Microsoft Moles\bin\moles.runner.exe" /runner:"%ProgramFiles%\Gallio\bin\Gallio.Echo.exe" "Gallio.Moles.Demo.dll" /args:/r:IsolatedAppDomain /args:/filter:"ExactType:TestFixture and Member:ReadFileContentWithMoles" -- Note: When using the command line with Echo (Gallio’s console runner), be sure to always include the IsolatedAppDomain option, otherwise the tests won’t use the instrumentation callbacks! -- License issues As I already said, the free mocking frameworks can mock only interfaces and virtual methods. if you want to mock other things, you need the Typemock Isolator tool for that, which comes with license costs (Although these ‘costs’ are ridiculously low compared to the value that such a tool can bring to a software project, spending money often is a considerable gateway hurdle in real life...).  The Moles framework also is not totally free, but comes with the same license conditions as the (closely related) Pex framework: It is free for academic/non-commercial use only, to use it in a ‘real’ software project requires an MSDN Subscription (from VS2010pro on). The demo solution The sample solution (VS 2008) can be downloaded from here. It contains the Gallio.Moles.dll which provides the here described Moled attribute, the above mentioned R#-template (moled_cmd.xml) and a test fixture containing the above described use case scenarios. To run it, you need the Gallio framework (download) and Microsoft Moles (download) being installed in the default locations. Happy testing…

    Read the article

  • Microsoft Moles release date

    - by DotnetDude
    Does anyone know when MS Moles will have a Release candidate? I am hesitant of using it in the Production system without knowing which direction it will head. Also, can Moles be used without using Pex? Thanks

    Read the article

  • Unit Testing with NUnit and Moles Redux

    - by João Angelo
    Almost two years ago, when Moles was still being packaged alongside Pex, I wrote a post on how to run NUnit tests supporting moled types. A lot has changed since then and Moles is now being distributed independently of Pex, but maintaining support for integration with NUnit and other testing frameworks. For NUnit the support is provided by an addin class library (Microsoft.Moles.NUnit.dll) that you need to reference in your test project so that you can decorate yours tests with the MoledAttribute. The addin DLL must also be placed in the addins folder inside the NUnit installation directory. There is however a downside, since Moles and NUnit follow a different release cycle and the addin DLL must be built against a specific NUnit version, you may find that the release included with the latest version of Moles does not work with your version of NUnit. Fortunately the code for building the NUnit addin is supplied in the archive (moles.samples.zip) that you can found in the Documentation folder inside the Moles installation directory. By rebuilding the addin against your specific version of NUnit you are able to support any version. Also to note that in Moles 0.94.51023.0 the addin code did not support the use of TestCaseAttribute in your moled tests. However, if you need this support, you need to make just a couple of changes. Change the ITestDecorator.Decorate method in the MolesAddin class: Test ITestDecorator.Decorate(Test test, MemberInfo member) { SafeDebug.AssumeNotNull(test, "test"); SafeDebug.AssumeNotNull(member, "member"); bool isTestFixture = true; isTestFixture &= test.IsSuite; isTestFixture &= test.FixtureType != null; bool hasMoledAttribute = true; hasMoledAttribute &= !SafeArray.IsNullOrEmpty( member.GetCustomAttributes(typeof(MoledAttribute), false)); if (!isTestFixture && hasMoledAttribute) { return new MoledTest(test); } return test; } Change the Tests property in the MoledTest class: public override System.Collections.IList Tests { get { if (this.test.Tests == null) { return null; } var moled = new List<Test>(this.test.Tests.Count); foreach (var test in this.test.Tests) { moled.Add(new MoledTest((Test)test)); } return moled; } } Disclaimer: I only tested this implementation against NUnit 2.5.10.11092 version. Finally you just need to run the NUnit console runner through the Moles runner. A quick example follows: moles.runner.exe [Tests.dll] /r:nunit-console.exe /x86 /args:[NUnitArgument1] /args:[NUnitArgument2]

    Read the article

  • How Moles Isolation framework is implemented?

    - by Buu Nguyen
    Moles is an isolation framework created by Microsoft. A cool feature of Moles is that it can "mock" static/non-virtual methods and sealed classes (which is not possible with frameworks like Moq). Below is the quick demonstration of what Moles can do: Assert.AreNotEqual(new DateTime(2012, 1, 1), DateTime.Now); // MDateTime is part of Moles; the below will "override" DateTime.Now's behavior MDateTime.NowGet = () => new DateTime(2012, 1, 1); Assert.AreEqual(new DateTime(2012, 1, 1), DateTime.Now); Seems like Moles is able to modify the CIL body of things like DateTime.Now at runtime. Since Moles isn't open-source, I'm curious to know which mechanism Moles uses in order to modify methods' CIL at runtime. Can anyone shed any light?

    Read the article

  • JustMock and Moles – A short overview for TDD alpha geeks

    - by RoyOsherove
    People have been lurking near my house, asking me to write something about Moles and JustMock, so I’ll try to be as objective as possible, taking in the fact that I work at Typemock. If I were NOT working at Typemock I’d write: JustMock JustMock tries to be Typemock at so many levels it’s not even funny. Technically they work the same and the API almost looks like it’s a search and replace work based on the Isolator API (awesome compliment!), but JustMock still has too many growing pains and bugs to be usable. Also, JustMock is missing alot of the legacy abilities such as Non public faking, faking all types and various other things that are really needed in real legacy code. Biggest thing (in terms of isolation integration) is that it does not integrate with other profilers such as coverage, NCover etc.) When JustMock comes out of beta, I feel that it should cost about half as Isolator costs, as it currently provides about half the abilities. Moles Moles is an addon of Pex and was originally only intended to work within the Pex environment. It started as a research project and now it’s a power-tool for VS (so it’s a separate install) Now it’s it’s own little stubbing framework. It’s not really an Isolation framework in the classic sense, because it does not provide any kind of API built in to verify object interactions. You have to use manual flags all on your own to do that. It generates two types of classes per assembly: Manual Stubs(just like you’d hand code them) and Mole classes. Each Mole class is a special API to change and break the behavior that the corresponding type. so MDateTime is how you change behavior for DateTime. In that sense the API is al over the place, and it can become highly unreadable and unmentionable over time in your test. Also, the Moles API isn’t really designed to deal with real Legacy code. It only deals with public types and methods. anything internal or private is ignored and you can’t change its behavior. You also can’t control static constructors. That takes about 95% of legacy scenarios out of the picture if that’s what you’re trying to use it for. Personally, I found it hard to get used to the idea of two parallel APIs for different abilities, and when to choose which. and I know this stuff. I would expect more usability from the API to make it more widely used. I don’t think that Moles in planning to go that route. Publishing it as an Isolation framework is really an afterthought of a tool that was design with a specific task in mind, and generic Isolation isn’t it. it’s only hope is DEQ – a simple code example that shows a simple Isolation API built on the Moles generic engine. Moles can and should be used for very simple cases of detouring functionality such a simple static methods or interfaces and virtual functions (like rhinomock and MOQ do).   Oh, Wait. Ah, good thing I work at Typemock. I won’t write all that. I’ll just write: JustMock and Moles are great tools that enlarge the market space for isolation related technologies, and they prove that the idea of productivity and unit testing can go hand in hand and get people hooked. I look forward to compete with them at this growing market.

    Read the article

  • Anyone using Moles / Pex in production?

    - by dferraro
    Hi all, I did search the forum and did not find a similar question. I'm looking to make a final decision on our mocking framework of choice moving forward as a best practice - I've decided on Moq... untill I just recently discovered MS has finally created a mocking framework called Moles which seems to work similar to TypeMock via the profiler API sexyness etc.. There's a million 'NMock vs Moq vs TypeMock vs Rhino....' threads on here. But I never see Moles involved.In fact, I did not even know if its existence until a short time ago. Anyone using it? In Production? Anyone dump their old mocking framework for it, and if so, which one? How did it compare to ther mocking frameworks you've used? thanks.. ps, we are using VS2008 and are moving to 2010 shortly.

    Read the article

  • What to put as the Provider for a mocked IQueryable

    - by Vaccano
    I am working with Moles and mocking a System.Data.Linq.Table. I got it constructing fine, but when I use it, it wants IQueryable.Provider to be mocked (moled) as well. I just want it to use normal Linq To Objects. Any idea what that would be? Here is the syntax I can use: MTable<User> userTable = new System.Data.Linq.Moles.MTable<User>(); userTable.Bind(new List<User> { UserObjectHelper.TestUser() }); // this is the line that needs help MolesDelegates.Func<IQueryProvider> provider = //Insert provider here! ^ userTable.ProviderSystemLinqIQueryableget = provider | | | what can I put here? ----------------------------------------+

    Read the article

  • JustMock and Moles A short overview for TDD alpha geeks

    People have been lurking near my house, asking me to write something about Moles and JustMock, so Ill try to be as objective as possible, taking in the fact that I work at Typemock. If I were NOT working at Typemock Id write: JustMock JustMock tries to be Typemock at so many levels its not even funny. Technically they work the same and the API almost looks like its a search and replace work based on the Isolator API (awesome compliment!), but JustMock still has too many growing pains and bugs...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Using MS Moles with datacontext and stored procedures without using a Connection string.

    - by Brian
    I have just begun to work with MS Moles for testing and I have followed the idea/pattern in which jcollum(thanks) uses a Mole for a table in this stackoverflow question here. But I am having a problem as I do not want to have to pass a connection string when I use the datasource as such: using (TheDataContext dataContext = new TheDataContext(myConnectionString)) { dataContext.ExecuteStoredprocedure(value, ref ValueExists); } I really like the fact that I just need to mole the table and everything else is done for me. I realize I could just mole the ExecuteStoredProcedure method, but I am wondering if I could just somehow avoid the sql exception I am getting here when I do not pass in the connection string. Or, if I there is a better way to do this? Therefore, does anyone have a solution so that I can avoid placing in the connection string? Thanks in advance.

    Read the article

  • Why null reference exception in SetMolePublicInstance?

    - by OldGrantonian
    I get a "null reference" exception in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, null); The program builds and compiles correctly. There are no complaints about any of the parameters to the method. Here's the specification of SetMolePublicInstance, from the object browser: SetMolePublicInstance(System.Delegate _stub, System.Type receiverType, object _receiver, string name, params System.Type[] parameterTypes) Here are the parameter values for "Locals": + stub {Method = {System.String <StaticMethodUnitTestWithDeq>b__0()}} System.Func<string> + receiverType {Name = "OrigValue" FullName = "OrigValueP.OrigValue"} System.Type {System.RuntimeType} objReceiver {OrigValueP.OrigValue} object {OrigValueP.OrigValue} name "TestString" string parameterTypes null object[] I know that TestString() takes no parameters and returns string, so as a starter to try to get things working, I specified "null" for the final parameter to SetMolePublicInstance. As already mentioned, this compiles OK. Here's the stack trace: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.ExtendedReflection.Collections.Indexable.ConvertAllToArray[TInput,TOutput](TInput[] array, Converter`2 converter) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMole(Delegate _stub, Type receiverType, Object _receiver, String name, MoleBindingFlags flags, Type[] parameterTypes) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(Delegate _stub, Type receiverType, Object _receiver, String name, Type[] parameterTypes) at DeqP.Deq.Replace[T](Func`1 stub, Type receiverType, Object objReceiver, String name) in C:\0VisProjects\DecP_04\DecP\DeqC.cs:line 38 at DeqPTest.DecCTest.StaticMethodUnitTestWithDeq() in C:\0VisProjects\DecP_04\DecPTest\DeqCTest.cs:line 28 at Starter.Start.Main(String[] args) in C:\0VisProjects\DecP_04\Starter\Starter.cs:line 14 Press any key to continue . . . To avoid the null parameter, I changed the final "null" to "parameterTypes" as in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, parameterTypes); I then tried each of the following (before the line): int[] parameterTypes = null; // if this is null, I don't think the type will matter int[] parameterTypes = new int[0]; object[] parameterTypes = new object[0]; // this would allow for various parameter types All three attempts produce a red squiggly line under the entire line for SetMolePublicInstance Mouseover showed the following message: The best overloaded method match for 'Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(System.Delegate, System.Type, object, string, params System.Type[])' has some invalid arguments. I'm assuming that the first four arguments are OK, and that the problem is with the params array.

    Read the article

  • PEX - are you licenced for it?

    - by TATWORTH
    There is an interesting artcile about PEX at http://blogs.msdn.com/b/ukmsdn/archive/2011/02/22/featured-article-pex-and-visual-studio.aspx PEX can be downloaded from http://research.microsoft.com/en-us/projects/pex/downloads.aspx The licence conditions are: "Pex and Moles are Power Tools available for commercial use for MSDN subscribers. Moles is also available separately for commercial use without requiring an MSDN subscription. Pex and Moles are also available for academic and non-commercial use." I note with interest that it is now available to MSDN subscribers. If I recall correctly it used to be only available to VS Team versions.

    Read the article

  • Compiz command plugin won't register keyboard shortcuts

    - by David Moles
    Per this discussion I've enabled the Compiz commands plugin in order to try to bind some keyboard shortcuts to wmctrl actions. CCSM captures my keystrokes just fine, but no matter what keystroke I try or what command I bind it to (everything from my original intention of binding Super-1, Super-2 etc. to wmctrl -o 0,0, wmctrl -o 2560,0, etc., to binding Ctrl-Alt-Shift-L to gnome-terminal). Basic compiz shortcuts for window switching and so on -- even custom ones -- seem to work fine, but the command plugin doesn't seem to be working at all. I also notice the following symptom: when I open the keyboard shortcut tab in CCSM, the keyboard shortcuts often at first appear blank, though if you click on the blank button, the correct value is still there. Also possibly related, I've noticed that gnome-terminal doesn't seem to notice the Super key, though other apps (e.g. CCSM, Emacs) register it fine. Anyway, it seems like something's eating my keystrokes. Any ideas?

    Read the article

  • In Jetty, can NCSARequestLog be configured to auto-detect the time zone?

    - by David Moles
    It looks as though in 2003 or so NCSARequestLog would pick up the system time zone using TimeZone.getDefault().getID(), but in more recent versions it seems as though it's hard-coded to GMT, unless you override it in jetty.xml or programmatically. If true, this kind of annoying, since it means if you don't want GMT logging you have to edit jetty.xml for every installation (not to mention twice a year for daylight saving time). Is there a workaround that will let Jetty pick the time zone up from the system? (X-posted to Stack Overflow.)

    Read the article

  • Compiz command plugin won't register keyboard shortcuts

    - by David Moles
    Per this discussion I've enabled the Compiz commands plugin in order to try to bind some keyboard shortcuts to wmctrl actions. CCSM captures my keystrokes just fine, but no matter what keystroke I try or what command I bind it to (everything from my original intention of binding Super-1, Super-2 etc. to wmctrl -o 0,0, wmctrl -o 2560,0, etc., to binding Ctrl-Alt-Shift-L to gnome-terminal). Basic compiz shortcuts for window switching and so on -- even custom ones -- seem to work fine, but the command plugin doesn't seem to be working at all. I also notice the following symptom: when I open the keyboard shortcut tab in CCSM, the keyboard shortcuts often at first appear blank, though if you click on the blank button, the correct value is still there. Also possibly related, I've noticed that gnome-terminal doesn't seem to notice the Super key, though other apps (e.g. CCSM, Emacs) register it fine. Anyway, it seems like something's eating my keystrokes. Any ideas?

    Read the article

  • Enabling Compiz Viewport Switcher key bindings

    - by David Moles
    I'm running compiz 0.8.2 with compizconfig on Scientific Linux 6.2 with Gnome 2.28.2. In the compizconfig "General Options" I have "Desktop Size" set as follows: Horizontal Virtual Size: 6 Vertical Virtual Size: 1 Number of Desktops: 1 This gets me the layout I want, i.e. 6 workspaces in a horizontal layout. Ctrl-alt-cursor-keys work fine for switching between them. However, I can't figure out how to get key bindings for specific workspaces. I've tried enabling "Viewport Switcher" in compizconfig, and tried various combinations both in "Number-based viewport switching" and "Go to specific viewport", to no apparent effect. My first thought was that something else was eating the specific key bindings I chose, but I think I've tried every combination of shift, control, alt and super (i.e., the Windows key) by now. I tried setting 6 desktops under "General Options" instead of one desktop with horizontal virtual size 6, but that doesn't seem to make a difference either. What am I missing?

    Read the article

  • Best way to use mod_rewrite to replace WordPress pages with static files

    - by David Moles
    Here's the situation: I've got an old WordPress installation that I'd like to archive as static files, but I'd also like to preserve old URLs. I've already created the static archive with wget and sorted out the filenames and links. Now I'd like to configure Apache to intercept requests for the old dynamic URL and replace them with the new static one, e.g.: http://www.example.org/log/?p=1234 or http://www.example.org/log/index.php?p=1234 should redirect to http://www.example.org/log/archives/1234.html I've tried adding the following to the VirtualHost config for example.org, but to no effect -- I just get the PHP page. RewriteCond %{REQUEST_URI} /log/ RewriteCond %{QUERY_STRING} p=([^&;]*) RewriteRule ^/$ http://%{SERVER_NAME}/log/archives/%1.html [R,L] I've enabled logging and I can see what look like other rules being applied, but not this one. None of my other guesses at match patterns for %{REQUEST_URI} seem to have any effect either (log, log/, log.*, even .*). I'm new to mod_rewrite and this is mostly cargo cult, so I'm pretty sure I've gotten it wrong. Anyone know what I should be doing here?

    Read the article

  • Enabling Compiz Viewport Switcher key bindings

    - by David Moles
    I'm running compiz 0.8.2 with compizconfig on Scientific Linux 6.2 with Gnome 2.28.2. In the compizconfig "General Options" I have "Desktop Size" set as follows: Horizontal Virtual Size: 6 Vertical Virtual Size: 1 Number of Desktops: 1 This gets me the layout I want, i.e. 6 workspaces in a horizontal layout. Ctrl-alt-cursor-keys work fine for switching between them. However, I can't figure out how to get key bindings for specific workspaces. I've tried enabling "Viewport Switcher" in compizconfig, and tried various combinations both in "Number-based viewport switching" and "Go to specific viewport", to no apparent effect. My first thought was that something else was eating the specific key bindings I chose, but I think I've tried every combination of shift, control, alt and super (i.e., the Windows key) by now. I tried setting 6 desktops under "General Options" instead of one desktop with horizontal virtual size 6, but that doesn't seem to make a difference either. What am I missing?

    Read the article

  • Unit Testing DateTime – The Crazy Way

    - by João Angelo
    We all know that the process of unit testing code that depends on DateTime, particularly the current time provided through the static properties (Now, UtcNow and Today), it’s a PITA. If you go ask how to unit test DateTime.Now on stackoverflow I’ll bet that you’ll get two kind of answers: Encapsulate the current time in your own interface and use a standard mocking framework; Pull out the big guns like Typemock Isolator, JustMock or Microsoft Moles/Fakes and mock the static property directly. Now each alternative has is pros and cons and I would have to say that I glean more to the second approach because the first adds a layer of abstraction just for the sake of testability. However, the second approach depends on commercial tools that not every shop wants to buy or in the not so friendly Microsoft Moles. (Sidenote: Moles is now named Fakes and it will ship with VS 2012) This tends to leave people without an acceptable and simple solution so after reading another of these types of questions in SO I came up with yet another alternative, one based on the first alternative that I presented here but tries really hard to not get in your way with yet another layer of abstraction. So, without further dues, I present you, the Tardis. The Tardis is single section of conditionally compiled code that overrides the meaning of the DateTime expression inside a single class. You still get the normal coding experience of using DateTime all over the place, but in a DEBUG compilation your tests will be able to mock every static method or property of the DateTime class. An example follows, while the full Tardis code can be downloaded from GitHub: using System; using NSubstitute; using NUnit.Framework; using Tardis; public class Example { public Example() : this(string.Empty) { } public Example(string title) { #if DEBUG this.DateTime = DateTimeProvider.Default; this.Initialize(title); } internal IDateTimeProvider DateTime { get; set; } internal Example(string title, IDateTimeProvider provider) { this.DateTime = provider; #endif this.Initialize(title); } private void Initialize(string title) { this.Title = title; this.CreatedAt = DateTime.UtcNow; } private string title; public string Title { get { return this.title; } set { this.title = value; this.UpdatedAt = DateTime.UtcNow; } } public DateTime CreatedAt { get; private set; } public DateTime UpdatedAt { get; private set; } } public class TExample { public void T001() { // Arrange var tardis = Substitute.For<IDateTimeProvider>(); tardis.UtcNow.Returns(new DateTime(2000, 1, 1, 6, 6, 6)); // Act var sut = new Example("Title", tardis); // Assert Assert.That(sut.CreatedAt, Is.EqualTo(tardis.UtcNow)); } public void T002() { // Arrange var tardis = Substitute.For<IDateTimeProvider>(); var sut = new Example("Title", tardis); tardis.UtcNow.Returns(new DateTime(2000, 1, 1, 6, 6, 6)); // Act sut.Title = "Updated"; // Assert Assert.That(sut.UpdatedAt, Is.EqualTo(tardis.UtcNow)); } } This approach is also suitable for other similar classes with commonly used static methods or properties like the ConfigurationManager class.

    Read the article

  • In Jetty, can NCSARequestLog be configured to auto-detect the time zone?

    - by David Moles
    It looks as though in 2003 or so NCSARequestLog would pick up the system time zone using TimeZone.getDefault().getID(), but in more recent versions it seems as though it's hard-coded to GMT, unless you override it in jetty.xml or programmatically. If true, this kind of annoying, since it means if you don't want GMT logging you have to edit jetty.xml for every installation (not to mention twice a year for daylight saving time). Is there a workaround that will let Jetty pick the time zone up from the system?

    Read the article

  • Null-free "maps": Is a callback solution slower than tryGet()?

    - by David Moles
    In comments to "How to implement List, Set, and Map in null free design?", Steven Sudit and I got into a discussion about using a callback, with handlers for "found" and "not found" situations, vs. a tryGet() method, taking an out parameter and returning a boolean indicating whether the out parameter had been populated. Steven maintained that the callback approach was more complex and almost certain to be slower; I maintained that the complexity was no greater and the performance at worst the same. But code speaks louder than words, so I thought I'd implement both and see what I got. The original question was fairly theoretical with regard to language ("And for argument sake, let's say this language don't even have null") -- I've used Java here because that's what I've got handy. Java doesn't have out parameters, but it doesn't have first-class functions either, so style-wise, it should suck equally for both approaches. (Digression: As far as complexity goes: I like the callback design because it inherently forces the user of the API to handle both cases, whereas the tryGet() design requires callers to perform their own boilerplate conditional check, which they could forget or get wrong. But having now implemented both, I can see why the tryGet() design looks simpler, at least in the short term.) First, the callback example: class CallbackMap<K, V> { private final Map<K, V> backingMap; public CallbackMap(Map<K, V> backingMap) { this.backingMap = backingMap; } void lookup(K key, Callback<K, V> handler) { V val = backingMap.get(key); if (val == null) { handler.handleMissing(key); } else { handler.handleFound(key, val); } } } interface Callback<K, V> { void handleFound(K key, V value); void handleMissing(K key); } class CallbackExample { private final Map<String, String> map; private final List<String> found; private final List<String> missing; private Callback<String, String> handler; public CallbackExample(Map<String, String> map) { this.map = map; found = new ArrayList<String>(map.size()); missing = new ArrayList<String>(map.size()); handler = new Callback<String, String>() { public void handleFound(String key, String value) { found.add(key + ": " + value); } public void handleMissing(String key) { missing.add(key); } }; } void test() { CallbackMap<String, String> cbMap = new CallbackMap<String, String>(map); for (int i = 0, count = map.size(); i < count; i++) { String key = "key" + i; cbMap.lookup(key, handler); } System.out.println(found.size() + " found"); System.out.println(missing.size() + " missing"); } } Now, the tryGet() example -- as best I understand the pattern (and I might well be wrong): class TryGetMap<K, V> { private final Map<K, V> backingMap; public TryGetMap(Map<K, V> backingMap) { this.backingMap = backingMap; } boolean tryGet(K key, OutParameter<V> valueParam) { V val = backingMap.get(key); if (val == null) { return false; } valueParam.value = val; return true; } } class OutParameter<V> { V value; } class TryGetExample { private final Map<String, String> map; private final List<String> found; private final List<String> missing; public TryGetExample(Map<String, String> map) { this.map = map; found = new ArrayList<String>(map.size()); missing = new ArrayList<String>(map.size()); } void test() { TryGetMap<String, String> tgMap = new TryGetMap<String, String>(map); for (int i = 0, count = map.size(); i < count; i++) { String key = "key" + i; OutParameter<String> out = new OutParameter<String>(); if (tgMap.tryGet(key, out)) { found.add(key + ": " + out.value); } else { missing.add(key); } } System.out.println(found.size() + " found"); System.out.println(missing.size() + " missing"); } } And finally, the performance test code: public static void main(String[] args) { int size = 200000; Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < size; i++) { String val = (i % 5 == 0) ? null : "value" + i; map.put("key" + i, val); } long totalCallback = 0; long totalTryGet = 0; int iterations = 20; for (int i = 0; i < iterations; i++) { { TryGetExample tryGet = new TryGetExample(map); long tryGetStart = System.currentTimeMillis(); tryGet.test(); totalTryGet += (System.currentTimeMillis() - tryGetStart); } System.gc(); { CallbackExample callback = new CallbackExample(map); long callbackStart = System.currentTimeMillis(); callback.test(); totalCallback += (System.currentTimeMillis() - callbackStart); } System.gc(); } System.out.println("Avg. callback: " + (totalCallback / iterations)); System.out.println("Avg. tryGet(): " + (totalTryGet / iterations)); } On my first attempt, I got 50% worse performance for callback than for tryGet(), which really surprised me. But, on a hunch, I added some garbage collection, and the performance penalty vanished. This fits with my instinct, which is that we're basically talking about taking the same number of method calls, conditional checks, etc. and rearranging them. But then, I wrote the code, so I might well have written a suboptimal or subconsicously penalized tryGet() implementation. Thoughts?

    Read the article

  • Doing without partial commits the "Mercurial way"

    - by David Moles
    Subversion shop considering switching to Mercurial, trying to figure out in advance what all the complaints from developers are going to be. There's one fairly common use case here that I can't see how to handle. I'm working on some largish feature, and I have a significant part of the code -- or possibly several significant parts of the code -- in pieces all over the garage floor, totally unsuitable for checkin, maybe not even compiling. An urgent bugfix request comes in. The fix is nice and local and doesn't touch any of the code I've been working on. I make the fix in my working copy. Now what? I've looked at "Mercurial cherry picking changes for commit" and "best practices in mercurial: branch vs. clone, and partial merges?" and all the suggestions seem to be extensions of varying complexity, from Record and Shelve to Queues. The fact that there apparently isn't any core functionality for this makes me suspect that in some sense this working style is Doing It Wrong. What would a Mercurial-like solution to this use case look like?

    Read the article

  • What's the easiest way to implement background downloading in Wicket?

    - by David Moles
    I've got a simple Wicket form that lets users select some data and then download a ZIP file (generated on the fly) containing what they asked for. Currently the form button's onSubmit() method looks something like this: public void onSubmit() { IResourceStream stream = /* assemble the data they asked for ... */ ; ResourceStreamRequestTarget target = new ResourceStreamRequestTarget(stream); target.setFileName("download.zip"); RequestCycle.get().setRequestTarget(target); } This works, but of course the request stops there and it's impossible to display any other feedback to the user. What I'd like to have is something like the typical "Your requested download [NAME] should begin automatically. If not, click this link." Ideally, still displaying the same page, so the user can immediately select some different data and download that as well. I imagine it's possible to do this using Wicket's Ajax classes, but I've managed to avoid having to use them so far, and it's not immediately obvious to me how. What's my quickest way out, here?

    Read the article

  • How would you TDD the functionality of getting the corresponding process of a running windows service?

    - by Matt Spinelli
    Purpose Over the last year or more I've been learning unit testing via books I've read recently like The Art of Unit Testing, Working Effectively with Legacy Code, and others. I've also been using unit tests, mocking frameworks, and the like, periodically at work and definitely see the value. However, I'm still having a hard time wrapping my mind around TDD (as opposed to TAD) when the situation calls for code that is gong to mostly use external API calls. Problem to solve Get the process associated with a windows service using the service name. example: Function GetProcess(ByVal serviceName As String) As Process Rules Show each major iteration in production & test code using TDD No need to see any other code or configuration that is required to get things to run. Just curious about the interfaces, concrete classes, and test methods. C# or VB.NET Must use the .Net framework regarding services/processes (i.e. System.Diagnostics.Process) Test Frameworks: Nunit or MSTest Isolation Frameworks: Moq, Rhino Mock, or Microsoft Moles Must write true unit tests (no integration tests) Additional notes As far as I can tell there are two approaches design wise. Use an Inversion of Control approach along with using the Adapter and/or Facade patterns to wrap the underlying .net framework objects dealing with processes and services. Keep the .net framework code in the class containing the Get Process method and use code detouring (interception) via Microsoft Moles to isolate the hard dependencies from the method under test.

    Read the article

1 2  | Next Page >