Search Results

Search found 270 results on 11 pages for 'joao pedro portelinha'.

Page 3/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • 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

  • Code Trivia #6

    - by João Angelo
    It’s time for yet another code trivia and it’s business as usual. What will the following program output to the console? using System; using System.Drawing; using System.Threading; class Program { [ThreadStatic] static Point Mark = new Point(1, 1); static void Main() { Thread.CurrentThread.Name = "A"; MoveMarkUp(); var helperThread = new Thread(MoveMarkUp) { Name = "B" }; helperThread.Start(); helperThread.Join(); } static void MoveMarkUp() { Mark.Y++; Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, Mark); } }

    Read the article

  • Code Trivia #7

    - by João Angelo
    Lets go for another code trivia, it’s business as usual, you just need to find what’s wrong with the following code: static void Main(string[] args) { using (var file = new FileStream("test", FileMode.Create) { WriteTimeout = 1 }) { file.WriteByte(0); } } TIP: There’s something very wrong with this specific code and there’s also another subtle problem that arises due to how the code is structured.

    Read the article

  • Assembly Resources Expression Builder

    - by João Angelo
    In ASP.NET you can tackle the internationalization requirement by taking advantage of native support to local and global resources used with the ResourceExpressionBuilder. But with this approach you cannot access public resources defined in external assemblies referenced by your Web application. However, since you can extend the .NET resource provider mechanism and create new expression builders you can workaround this limitation and use external resources in your ASPX pages much like you use local or global resources. Finally, if you are thinking, okay this is all very nice but where’s the code I can use? Well, it was too much to publish directly here so download it from Helpers.Web@Codeplex, where you also find a sample on how to configure and use it.

    Read the article

  • Can't add repos after upgrading to 12.04 LTS

    - by joao
    I'm a complete Linux newbie. I've just upgraded from 10.04 to 12.04 LTS and all sorts of things have started to go wrong. One main problem is the fact that I can't add repos. Example: sudo add-apt-repository ppa:team-xbmc outputs: Traceback (most recent call last): File "/usr/bin/add-apt-repository", line 8, in <module> from softwareproperties.SoftwareProperties import SoftwareProperties File "/usr/lib/python2.7/dist-packages/softwareproperties/SoftwareProperties.py", line 53, in <module> from ppa import AddPPASigningKeyThread, expand_ppa_line File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 27, in <module> import pycurl ImportError: librtmp.so.0: cannot open shared object file: No such file or directory /etc/apt/sources.list # deb cdrom:[Ubuntu 10.04.1 LTS _Lucid Lynx_ - Release i386 (20100816.1)]/ lucid main restricted # deb cdrom:[Ubuntu 10.04.1 LTS _Lucid Lynx_ - Release i386 (20100816.1)]/ maverick main restricted # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://archive.ubuntu.com/ubuntu precise main restricted deb-src http://archive.ubuntu.com/ubuntu precise main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://archive.ubuntu.com/ubuntu precise-updates main restricted deb-src http://archive.ubuntu.com/ubuntu precise-updates main restricted ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://archive.ubuntu.com/ubuntu precise universe deb-src http://archive.ubuntu.com/ubuntu precise universe deb http://archive.ubuntu.com/ubuntu precise-updates universe deb-src http://archive.ubuntu.com/ubuntu precise-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://archive.ubuntu.com/ubuntu precise multiverse deb-src http://archive.ubuntu.com/ubuntu precise multiverse deb http://archive.ubuntu.com/ubuntu precise-updates multiverse deb-src http://archive.ubuntu.com/ubuntu precise-updates multiverse ## Uncomment the following two lines to add software from the 'backports' ## repository. ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. # deb-src http://pt.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe multiverse ## Uncomment the following two lines to add software from Canonical's ## 'partner' repository. ## This software is not part of Ubuntu, but is offered by Canonical and the ## respective vendors as a service to Ubuntu users. # deb http://archive.canonical.com/ubuntu lucid partner # deb-src http://archive.canonical.com/ubuntu lucid partner deb http://archive.ubuntu.com/ubuntu precise-security main restricted deb-src http://archive.ubuntu.com/ubuntu precise-security main restricted deb http://archive.ubuntu.com/ubuntu precise-security universe deb-src http://archive.ubuntu.com/ubuntu precise-security universe deb http://archive.ubuntu.com/ubuntu precise-security multiverse deb-src http://archive.ubuntu.com/ubuntu precise-security multiverse # deb http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main # disabled on upgrade to precise I have no clue what do do next. Should I just scrap this installation and start from scratch or is this fixable? librtmp.so.0 also shows up in error logs I've started to get from XBMC (I'm not sure if this is relevant info). Thanks in advance for any help you can give me!

    Read the article

  • Add a database to use with locate command

    - by Pedro Teran
    i would like to know if anyone knows how I can create a database of a file system on my computer. so I can choose this data base to search for files on this file system efficiently. I ask this question since in man locate I found that I can choose a database for a different file system. Also would be grate if /var/lib/mlocate/mlocate.db database can have the data of 2 disks any approach ideas or others would be greatly appreciated

    Read the article

  • How would it be if browsers natively *hosted* JavaScript frameworks? [closed]

    - by João Ramos
    More than 20 million websites nowadays are running jQuery and more than 1/5 of the top million websites are also doing so. What if we, as designers and developers, could take advantage of locally cached JavaScript libraries like jQuery, Prototype, script.aculo.us, etc? Wouldn't it be great if we could provide users with faster websites and experiences? EDIT: My apologies, I ment to ask how hould it be if browsers hosted JavaScript frameworks, not support them. Actually, there's no sense in my previous question. Sorry for that.

    Read the article

  • I'm an experienced PHP programmer, how would it be for me to learn and use Django and Ruby on Rails?

    - by João Paulo Apolinário Passos
    I'm an experienced PHP programmer, I still have lots to learn but I consider myself experienced. I sometimes use pure PHP and sometimes some framework like CodeIgniter. I always wanted to learn new technologies like Python and Ruby, and their best frameworks for web are Django and Ruby on Rails, but I want to ask to persons like me who migrated from PHP to some of this technologies if is it worth it; Thank you

    Read the article

  • Is there any practical use for the empty type in Common Lisp?

    - by Pedro Rodrigues
    The Common Lisp spec states that nil is the name of the empty type, but I've never found any situation in Common Lisp where I felt like the empty type was useful/necessary. Is it there just for completeness sake (and removing it wouldn't cause any harm to anyone)? Or is there really some practical use for the empty type in Common Lisp? If yes, then I would prefer an answer with code example. For example, in Haskell the empty type can be used when binding foreign data structures, to make sure that no one tries to create values of that type without using the data structure's foreign interface (although in this case, the type is not really empty).

    Read the article

  • Introducing NFakeMail

    - by João Angelo
    Ever had to resort to custom code to control emails sent by an application during integration and/or system testing? If you answered yes then you should definitely continue reading. NFakeMail makes it easier for developers to do integration/system testing on software that sends emails by providing a fake SMTP server. You’ll no longer have to manually validate the email sending process. It’s developed in C# and IronPython and targets the .NET 4.0 framework. With NFakeMail you can easily automate the testing of components that rely on sending mails while doing its job. Let’s take a look at some sample code, we start with a simple class containing a method that sends emails. class Notifier { public void Notify() { using (var smtpClient = new SmtpClient("localhost", 10025)) { smtpClient.Send("[email protected]", "[email protected]", "S1", "."); smtpClient.Send("[email protected]", "[email protected]", "S2", ".."); } } } Then to automate the tests for this method we only need to the following: [Test] public void Notify_T001() { using (var server = new FakeSmtpServer(10025)) { new Notifier().Notify(); // Verifies two messages are received in the next five seconds var messages = server.WaitForMessages(count: 2, timeout: 5000); // Verifies the message sender Debug.Assert(messages.All(m => m.From.Address == "[email protected]")); } } The created FakeSmtpServer instance will act as a simple SMTP server and intercept the messages sent by the Notifier class. It’s even possible to verify some fields of each intercepted message and by default all intercepted messages are saved to the file system in MIME format.

    Read the article

  • Visual Studio Macro – Identifier to String Literal

    - by João Angelo
    When implementing public methods with parameters it’s important to write boiler-plate code to do argument validation and throw exceptions when needed, ArgumentException and ArgumentNullException being the most recurrent. Another thing that is important is to correctly specify the parameter causing the exception through the proper exception constructor. In order to take advantage of IntelliSense completion in these scenarios I use a Visual Studio macro binded to a keyboard shortcut that converts the identifier at the cursor position to a string literal. And here’s the macro: Sub ConvertIdentifierToStringLiteral() Dim targetWord As String Dim document As EnvDTE.TextDocument document = CType(DTE.ActiveDocument.Object, EnvDTE.TextDocument) If document.Selection.Text.Length > 0 Then targetWord = document.Selection.Text document.Selection.ReplacePattern(targetWord, """" + targetWord + """") Else Dim cursorPoint As EnvDTE.TextPoint cursorPoint = document.Selection.ActivePoint() Dim editPointLeft As EnvDTE.EditPoint Dim editPointRight As EnvDTE.EditPoint editPointLeft = cursorPoint.CreateEditPoint() editPointLeft.WordLeft(1) editPointRight = editPointLeft.CreateEditPoint() editPointRight.WordRight(1) targetWord = editPointLeft.GetText(editPointRight) editPointLeft.ReplaceText(editPointRight, """" + targetWord + """", 0) End If End Sub

    Read the article

  • ASP.NET ViewState Tips and Tricks #1

    - by João Angelo
    In User Controls or Custom Controls DO NOT use ViewState to store non public properties. Persisting non public properties in ViewState results in loss of functionality if the Page hosting the controls has ViewState disabled since it can no longer reset values of non public properties on page load. Example: public class ExampleControl : WebControl { private const string PublicViewStateKey = "Example_Public"; private const string NonPublicViewStateKey = "Example_NonPublic"; // DO public int Public { get { object o = this.ViewState[PublicViewStateKey]; if (o == null) return default(int); return (int)o; } set { this.ViewState[PublicViewStateKey] = value; } } // DO NOT private int NonPublic { get { object o = this.ViewState[NonPublicViewStateKey]; if (o == null) return default(int); return (int)o; } set { this.ViewState[NonPublicViewStateKey] = value; } } } // Page with ViewState disabled public partial class ExamplePage : Page { protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.Example.Public = 10; // Restore Public value this.Example.NonPublic = 20; // Compile Error! } }

    Read the article

  • Default Parameters vs Method Overloading

    - by João Angelo
    With default parameters introduced in C# 4.0 one might be tempted to abandon the old approach of providing method overloads to simulate default parameters. However, you must take in consideration that both techniques are not interchangeable since they show different behaviors in certain scenarios. For me the most relevant difference is that default parameters are a compile time feature while method overloading is a runtime feature. To illustrate these concepts let’s take a look at a complete, although a bit long, example. What you need to retain from the example is that static method Foo uses method overloading while static method Bar uses C# 4.0 default parameters. static void CreateCallerAssembly(string name) { // Caller class - Invokes Example.Foo() and Example.Bar() string callerCode = String.Concat( "using System;", "public class Caller", "{", " public void Print()", " {", " Console.WriteLine(Example.Foo());", " Console.WriteLine(Example.Bar());", " }", "}"); var parameters = new CompilerParameters(new[] { "system.dll", "Common.dll" }, name); new CSharpCodeProvider().CompileAssemblyFromSource(parameters, callerCode); } static void Main() { // Example class - Foo uses overloading while Bar uses C# 4.0 default parameters string exampleCode = String.Concat( "using System;", "public class Example", "{{", " public static string Foo() {{ return Foo(\"{0}\"); }}", " public static string Foo(string key) {{ return \"FOO-\" + key; }}", " public static string Bar(string key = \"{0}\") {{ return \"BAR-\" + key; }}", "}}"); var compiler = new CSharpCodeProvider(); var parameters = new CompilerParameters(new[] { "system.dll" }, "Common.dll"); // Build Common.dll with default value of "V1" compiler.CompileAssemblyFromSource(parameters, String.Format(exampleCode, "V1")); // Caller1 built against Common.dll that uses a default of "V1" CreateCallerAssembly("Caller1.dll"); // Rebuild Common.dll with default value of "V2" compiler.CompileAssemblyFromSource(parameters, String.Format(exampleCode, "V2")); // Caller2 built against Common.dll that uses a default of "V2" CreateCallerAssembly("Caller2.dll"); dynamic caller1 = Assembly.LoadFrom("Caller1.dll").CreateInstance("Caller"); dynamic caller2 = Assembly.LoadFrom("Caller2.dll").CreateInstance("Caller"); Console.WriteLine("Caller1.dll:"); caller1.Print(); Console.WriteLine("Caller2.dll:"); caller2.Print(); } And if you run this code you will get the following output: // Caller1.dll: // FOO-V2 // BAR-V1 // Caller2.dll: // FOO-V2 // BAR-V2 You see that even though Caller1.dll runs against the current Common.dll assembly where method Bar defines a default value of “V2″ the output show us the default value defined at the time Caller1.dll compiled against the first version of Common.dll. This happens because the compiler will copy the current default value to each method call, much in the same way a constant value (const keyword) is copied to a calling assembly and changes to it’s value will only be reflected if you rebuild the calling assembly again. The use of default parameters is also discouraged by Microsoft in public API’s as stated in (CA1026: Default parameters should not be used) code analysis rule.

    Read the article

  • How can I set a second screen (DISPLAY=:0.1) as the default gnome display?

    - by Pedro Silva
    Due to various reasons, I have my main monitor set as the secondary display in xorg.conf. I would like to have gnome initialize metacity, gnome-panel as running primarily on :0.1, instead of :0.0. Is this possible at all? To clarify, this is a laptop with its LCD turned off. My main monitor is connected to the VGA out and is driven by the nouveau driver for NVIDIA; a secondary monitor is on a displaylink usb-vga donverter. The seconday monitor is set in xorg.conf as the primary display (no way around it). I can do things like DISPLAY=:0.1 gnome-terminal to run applications on the main monitor. My question is whether it is possible to do this (GNOME-) system-wide.

    Read the article

  • Can't Install Wine, held Packages

    - by Joao Seara
    I am getting this error: The following packages have unmet dependencies: udev : Depends: libudev1 (= 204-5ubuntu20.2) but 204-5ubuntu20.4 is to be installed E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages. I've tried to apt-get dist-upgrade and I got the same message: The following packages have been kept back: libudev1 udev 0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded. I am using ubuntu 64bits 14.04 Thank you guys!

    Read the article

  • Mobile Internet Modem Olivetti Olicard 155 does not work in Ubuntu 12.10

    - by João Fracassi
    I have a problem, I bought a 3G mobile modem, but does not work in Ubuntu 12.10, also did not work on Ubuntu 12.04. I installed the USB Modeswitch and has the same flaw, does not recognize the modem within the connection manager, I connect the modem to the USB port and wait up to 20 minutes and does not recognize the modem. I ran the command recognizes the modem and lsusb as "Bus 001 Device 007: ID 0b3c: C004 Olivetti TechCenter." Does anyone have this modem, you can help me solve the problem, or does anyone have a solution? Because the manufacturer does not support Linux and according to some forums usbmodeswitch supports esste model. Olivetti Olicard modem 155.

    Read the article

  • An Unusual UpdatePanel

    - by João Angelo
    The code you are about to see was mostly to prove a point, to myself, and probably has limited applicability. Nonetheless, in the remote possibility this is useful to someone here it goes… So this is a control that acts like a normal UpdatePanel where all child controls are registered as postback triggers except for a single control specified by the TriggerControlID property. You could basically achieve the same thing by registering all controls as postback triggers in the regular UpdatePanel. However with this, that process is performed automatically. Finally, here is the code: public sealed class SingleAsyncTriggerUpdatePanel : WebControl, INamingContainer { public string TriggerControlID { get; set; } [TemplateInstance(TemplateInstance.Single)] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate ContentTemplate { get; set; } public override ControlCollection Controls { get { this.EnsureChildControls(); return base.Controls; } } protected override void CreateChildControls() { if (string.IsNullOrWhiteSpace(this.TriggerControlID)) throw new InvalidOperationException( "The TriggerControlId property must be set."); this.Controls.Clear(); var updatePanel = new UpdatePanel() { ID = string.Concat(this.ID, "InnerUpdatePanel"), ChildrenAsTriggers = false, UpdateMode = UpdatePanelUpdateMode.Conditional, ContentTemplate = this.ContentTemplate }; updatePanel.Triggers.Add(new SingleControlAsyncUpdatePanelTrigger { ControlID = this.TriggerControlID }); this.Controls.Add(updatePanel); } } internal sealed class SingleControlAsyncUpdatePanelTrigger : UpdatePanelControlTrigger { private Control target; private ScriptManager scriptManager; public Control Target { get { if (this.target == null) { this.target = this.FindTargetControl(true); } return this.target; } } public ScriptManager ScriptManager { get { if (this.scriptManager == null) { var page = base.Owner.Page; if (page != null) { this.scriptManager = ScriptManager.GetCurrent(page); } } return this.scriptManager; } } protected override bool HasTriggered() { string asyncPostBackSourceElementID = this.ScriptManager.AsyncPostBackSourceElementID; if (asyncPostBackSourceElementID == this.Target.UniqueID) return true; return asyncPostBackSourceElementID.StartsWith( string.Concat(this.target.UniqueID, "$"), StringComparison.Ordinal); } protected override void Initialize() { base.Initialize(); foreach (Control control in FlattenControlHierarchy(this.Owner.Controls)) { if (control == this.Target) continue; bool isApplicableControl = false; isApplicableControl |= control is INamingContainer; isApplicableControl |= control is IPostBackDataHandler; isApplicableControl |= control is IPostBackEventHandler; if (isApplicableControl) { this.ScriptManager.RegisterPostBackControl(control); } } } private static IEnumerable<Control> FlattenControlHierarchy( ControlCollection collection) { foreach (Control control in collection) { yield return control; if (control.Controls.Count > 0) { foreach (Control child in FlattenControlHierarchy(control.Controls)) { yield return child; } } } } } You can use it like this, meaning that only the B2 button will trigger an async postback: <cc:SingleAsyncTriggerUpdatePanel ID="Test" runat="server" TriggerControlID="B2"> <ContentTemplate> <asp:Button ID="B1" Text="B1" runat="server" OnClick="Button_Click" /> <asp:Button ID="B2" Text="B2" runat="server" OnClick="Button_Click" /> <asp:Button ID="B3" Text="B3" runat="server" OnClick="Button_Click" /> <asp:Label ID="LInner" Text="LInner" runat="server" /> </ContentTemplate> </cc:SingleAsyncTriggerUpdatePanel>

    Read the article

  • Cannot access system after deleting passwd file

    - by joao rodrigo leao
    I was trying to change my user name and also my /home/username and my system started to crash. I deleted the passwd file but I had a backup named passwd_bkp. I tried to rename this passwd_bkp as passwd and it did not work. No commands were being executed... I was in a terminal window. I re-started my system and now I cannot login. The GRub loads two options: Linux and recovery mode. I tried to open a sessions as root but it says the file system is corrupted. I cannot access my files. Did I lose all my files?

    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

  • Enumerable Interleave Extension Method

    - by João Angelo
    A recent stackoverflow question, which I didn’t bookmark and now I’m unable to find, inspired me to implement an extension method for Enumerable that allows to insert a constant element between each pair of elements in a sequence. Kind of what String.Join does for strings, but maintaining an enumerable as the return value. Having done the single element part I got a bit carried away and ended up expanding it adding overloads to support interleaving elements of another sequence and support for a predicate to control when interleaving takes place. I have to confess that I did this for fun and now I can’t think of any real usage scenario, nonetheless, it may prove useful for someone. First a simple example: var target = new string[] { "(", ")", "(", ")" }; var result = target.Interleave(".", (f, s) => f == "("); // Prints: (.)(.) Console.WriteLine(String.Join(string.Empty, result)); And now the untested but documented implementation: using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class EnumerableExtensions { /// <summary> /// Iterates infinitely over a constant element. /// </summary> /// <typeparam name="T"> /// The type of element in the sequence. /// </typeparam> private class InfiniteSequence<T> : IEnumerable<T>, IEnumerator<T> { public InfiniteSequence(T element) { this.Element = element; } public T Element { get; private set; } public IEnumerator<T> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } T IEnumerator<T>.Current { get { return this.Element; } } void IDisposable.Dispose() { } object IEnumerator.Current { get { return this.Element; } } bool IEnumerator.MoveNext() { return true; } void IEnumerator.Reset() { } } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence. /// </summary> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="element"> /// The element used to perform the interleave operation. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="element"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, T element) { if (target == null) throw new ArgumentNullException("target"); if (element == null) throw new ArgumentNullException("element"); return InterleaveInternal(target, new InfiniteSequence<T>(element), (f, s) => true); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence. /// </summary> /// <remarks> /// The interleave operation is interrupted as soon as the <paramref name="target"/> sequence is exhausted; If the number of <paramref name="elements"/> to be interleaved are not enough to completely interleave the <paramref name="target"/> sequence then the remainder of the sequence is returned without being interleaved. /// </remarks> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="elements"> /// The elements used to perform the interleave operation. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="elements"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, IEnumerable<T> elements) { if (target == null) throw new ArgumentNullException("target"); if (elements == null) throw new ArgumentNullException("elements"); return InterleaveInternal(target, elements, (f, s) => true); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence that satisfy <paramref name="predicate"/>. /// </summary> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="element"> /// The element used to perform the interleave operation. /// </param> /// <param name="predicate"> /// A predicate used to assert if interleaving should occur between two target elements. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> or <paramref name="predicate"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="element"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, T element, Func<T, T, bool> predicate) { if (target == null) throw new ArgumentNullException("target"); if (element == null) throw new ArgumentNullException("element"); if (predicate == null) throw new ArgumentNullException("predicate"); return InterleaveInternal(target, new InfiniteSequence<T>(element), predicate); } /// <summary> /// Interleaves the specified <paramref name="element"/> between each pair of elements in the <paramref name="target"/> sequence that satisfy <paramref name="predicate"/>. /// </summary> /// <remarks> /// The interleave operation is interrupted as soon as the <paramref name="target"/> sequence is exhausted; If the number of <paramref name="elements"/> to be interleaved are not enough to completely interleave the <paramref name="target"/> sequence then the remainder of the sequence is returned without being interleaved. /// </remarks> /// <typeparam name="T"> /// The type of elements in the sequence. /// </typeparam> /// <param name="target"> /// The target sequence to be interleaved. /// </param> /// <param name="elements"> /// The elements used to perform the interleave operation. /// </param> /// <param name="predicate"> /// A predicate used to assert if interleaving should occur between two target elements. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> or <paramref name="element"/> or <paramref name="predicate"/> is a null reference. /// </exception> /// <returns> /// The <paramref name="target"/> sequence interleaved with the specified <paramref name="elements"/>. /// </returns> public static IEnumerable<T> Interleave<T>( this IEnumerable<T> target, IEnumerable<T> elements, Func<T, T, bool> predicate) { if (target == null) throw new ArgumentNullException("target"); if (elements == null) throw new ArgumentNullException("elements"); if (predicate == null) throw new ArgumentNullException("predicate"); return InterleaveInternal(target, elements, predicate); } private static IEnumerable<T> InterleaveInternal<T>( this IEnumerable<T> target, IEnumerable<T> elements, Func<T, T, bool> predicate) { var targetEnumerator = target.GetEnumerator(); if (targetEnumerator.MoveNext()) { var elementsEnumerator = elements.GetEnumerator(); while (true) { T first = targetEnumerator.Current; yield return first; if (!targetEnumerator.MoveNext()) yield break; T second = targetEnumerator.Current; bool interleave = true && predicate(first, second) && elementsEnumerator.MoveNext(); if (interleave) yield return elementsEnumerator.Current; } } } }

    Read the article

  • RemoveAll Dictionary Extension Method

    - by João Angelo
    Removing from a dictionary all the elements where the keys satisfy a set of conditions is something I needed to do more than once so I implemented it as an extension method to the IDictionary<TKey, TValue> interface. Here’s the code: public static class DictionaryExtensions { /// <summary> /// Removes all the elements where the key match the conditions defined by the specified predicate. /// </summary> /// <typeparam name="TKey"> /// The type of the dictionary key. /// </typeparam> /// <typeparam name="TValue"> /// The type of the dictionary value. /// </typeparam> /// <param name="dictionary"> /// A dictionary from which to remove the matched keys. /// </param> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the keys to remove. /// </param> /// <exception cref="ArgumentNullException"> /// dictionary is null /// <br />-or-<br /> /// match is null. /// </exception> /// <returns> /// The number of elements removed from the <see cref="IDictionary{TKey, TValue}"/>. /// </returns> public static int RemoveAll<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, Predicate<TKey> match) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (match == null) throw new ArgumentNullException("match"); var keysToRemove = dictionary.Keys.Where(k => match(k)).ToList(); if (keysToRemove.Count == 0) return 0; foreach (var key in keysToRemove) { dictionary.Remove(key); } return keysToRemove.Count; } }

    Read the article

  • Is there an official Ubuntu free support team?

    - by João Pinto
    I have found that there is an "Ubuntu Support Team" at https://launchpad.net/~ubuntu-helpteam but I am not sure it's official or active. Please note that I am not referring to bug fixing support, I am referring to the broader OS support, with people available to engage users needing support with a problem and drive it to a proper resolution. Is there an official team for this purpose with a clear scope and activity plan ?

    Read the article

  • Extended FindWindow

    - by João Angelo
    The Win32 API provides the FindWindow function that supports finding top-level windows by their class name and/or title. However, the title search does not work if you are trying to match partial text at the middle or the end of the full window title. You can however implement support for these extended search features by using another set of Win32 API like EnumWindows and GetWindowText. A possible implementation follows: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; public class WindowInfo { private IntPtr handle; private string className; internal WindowInfo(IntPtr handle, string title) { if (handle == IntPtr.Zero) throw new ArgumentException("Invalid handle.", "handle"); this.Handle = handle; this.Title = title ?? string.Empty; } public string Title { get; private set; } public string ClassName { get { if (className == null) { className = GetWindowClassNameByHandle(this.Handle); } return className; } } public IntPtr Handle { get { if (!NativeMethods.IsWindow(this.handle)) throw new InvalidOperationException("The handle is no longer valid."); return this.handle; } private set { this.handle = value; } } public static WindowInfo[] EnumerateWindows() { var windows = new List<WindowInfo>(); NativeMethods.EnumWindowsProcessor processor = (hwnd, lParam) => { windows.Add(new WindowInfo(hwnd, GetWindowTextByHandle(hwnd))); return true; }; bool succeeded = NativeMethods.EnumWindows(processor, IntPtr.Zero); if (!succeeded) return new WindowInfo[] { }; return windows.ToArray(); } public static WindowInfo FindWindow(Predicate<WindowInfo> predicate) { WindowInfo target = null; NativeMethods.EnumWindowsProcessor processor = (hwnd, lParam) => { var current = new WindowInfo(hwnd, GetWindowTextByHandle(hwnd)); if (predicate(current)) { target = current; return false; } return true; }; NativeMethods.EnumWindows(processor, IntPtr.Zero); return target; } private static string GetWindowTextByHandle(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException("Invalid handle.", "handle"); int length = NativeMethods.GetWindowTextLength(handle); if (length == 0) return string.Empty; var buffer = new StringBuilder(length + 1); NativeMethods.GetWindowText(handle, buffer, buffer.Capacity); return buffer.ToString(); } private static string GetWindowClassNameByHandle(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentException("Invalid handle.", "handle"); const int WindowClassNameMaxLength = 256; var buffer = new StringBuilder(WindowClassNameMaxLength); NativeMethods.GetClassName(handle, buffer, buffer.Capacity); return buffer.ToString(); } } internal class NativeMethods { public delegate bool EnumWindowsProcessor(IntPtr hwnd, IntPtr lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumWindows( EnumWindowsProcessor lpEnumFunc, IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetWindowText( IntPtr hWnd, StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int GetClassName( IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindow(IntPtr hWnd); } The access to the windows handle is preceded by a sanity check to assert if it’s still valid, but if you are dealing with windows out of your control then the window can be destroyed right after the check so it’s not guaranteed that you’ll get a valid handle. Finally, to wrap this up a usage, example: static void Main(string[] args) { var w = WindowInfo.FindWindow(wi => wi.Title.Contains("Test.docx")); if (w != null) { Console.Write(w.Title); } }

    Read the article

  • Jump-start Your Mind

    - by João Angelo
    I haven’t written in a while mostly because I’ve spent my time reading what others wrote and today I’m writing purely motivated by what I just finished reading. Mindfire: Big Ideas for Curious Mind by Scott Berkun was such a pleasure to read and ended up igniting parts of my mind which I have to admit were becoming a bit numb that I felt the urge to take some time to first say thank you to the author and then recommend it to all your curious minds out there. Now, go read it… it’s time well spent.

    Read the article

  • How to boot from a debootstrap based install?

    - by João Pinto
    I would like to boot a testing Ubuntu release from a directory (which contains a debootstrap based install). As far as I understand I just need someway to tell the boot process (initrd scripts?) that it should chroot() into the specified dir immediately after mounting the root partition, and then resume the regular upstart/init start. Could someone provide some instructions on how to achieve this?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >