Search Results

Search found 135 results on 6 pages for 'joao ramos'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • ASP.NET ViewState Tips and Tricks #2

    - by João Angelo
    If you need to store complex types in ViewState DO implement IStateManager to control view state persistence and reduce its size. By default a serializable object will be fully stored in view state using BinaryFormatter. A quick comparison for a complex type with two integers and one string property produces the following results measured using ASP.NET tracing: BinaryFormatter: 328 bytes in view state IStateManager: 28 bytes in view state BinaryFormatter sample code: // DO NOT [Serializable] public class Info { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class ExampleControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!this.Page.IsPostBack) { this.User = new Info { Id = 1, Name = "John Doe", Age = 27 }; } } public Info User { get { object o = this.ViewState["Example_User"]; if (o == null) return null; return (Info)o; } set { this.ViewState["Example_User"] = value; } } } IStateManager sample code: // DO public class Info : IStateManager { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } private bool isTrackingViewState; bool IStateManager.IsTrackingViewState { get { return this.isTrackingViewState; } } void IStateManager.LoadViewState(object state) { var triplet = (Triplet)state; this.Id = (int)triplet.First; this.Name = (string)triplet.Second; this.Age = (int)triplet.Third; } object IStateManager.SaveViewState() { return new Triplet(this.Id, this.Name, this.Age); } void IStateManager.TrackViewState() { this.isTrackingViewState = true; } } public class ExampleControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!this.Page.IsPostBack) { this.User = new Info { Id = 1, Name = "John Doe", Age = 27 }; } } public Info User { get; set; } protected override object SaveViewState() { return new Pair( ((IStateManager)this.User).SaveViewState(), base.SaveViewState()); } protected override void LoadViewState(object savedState) { if (savedState != null) { var pair = (Pair)savedState; this.User = new Info(); ((IStateManager)this.User).LoadViewState(pair.First); base.LoadViewState(pair.Second); } } }

    Read the article

  • Do Repeat Yourself in Unit Tests

    - by João Angelo
    Don’t get me wrong I’m a big supporter of the DRY (Don’t Repeat Yourself) Principle except however when it comes to unit tests. Why? Well, in my opinion a unit test should be a self-contained group of actions with the intent to test a very specific piece of code and should not depend on externals shared with other unit tests. In a typical unit test we can divide its code in two major groups: Preparation of preconditions for the code under test; Invocation of the code under test. It’s in the first group that you are tempted to refactor common code in several unit tests into helper methods that can then be called in each one of them. Another way to not duplicate code is to use the built-in infrastructure of some unit test frameworks such as SetUp/TearDown methods that automatically run before and after each unit test. I must admit that in the past I was guilty of both charges but what at first seemed a good idea since I was removing code duplication turnout to offer no added value and even complicate the process when a given test fails. We love unit tests because of their rapid feedback when something goes wrong. However, this feedback requires most of the times reading the code for the failed test. Given this, what do you prefer? To read a single method or wander through several methods like SetUp/TearDown and private common methods. I say it again, do repeat yourself in unit tests. It may feel wrong at first but I bet you won’t regret it later.

    Read the article

  • How to use XDMCP+GDM and Xnest?

    - by João Pinto
    I have been trying to enable XDMCP on GDM without much success. Following some instructions I have edited /etc/gdm/custom.conf and added: [daemon] RemoteGreeter=/usr/lib/gdm/gdm-xdmcp-chooser-slave [xdmcp] Enable=true Then restarted gdm and tried to connect both locally and from a remote system with: Xnest :1 -query localhost Xnest :1 -query remote_system_hostname I just get a black screen instead of the GDM window as expected. I am missing something ?

    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

  • 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

  • Agile sysadmin and devops - How to accomplish?

    - by Marco Ramos
    Nowadays, agile systems adminitration and devops are some of the most trending topics regarding systems administration and operations. Both these concepts are mainly focused on bridging the gap between operations/sysadmins and the projects (developers, business, etc). Even if you never heard of the devops concept, I'm sure that this topic is your concern too. So, what tools and techniques do you use to accomplish devops in you companies? I'm particularly interested in topics like change management, continous integration and automatization, but not only. Please share your thoughts. I'm looking forward to read your answers/opinions :)

    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

  • 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

  • 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

  • Shinken - Anyone using it?

    - by Marco Ramos
    I've recently discovered Shinken, which a new implementation of Nagios using python. Shinken "divides" Nagios in 5 different types of agents, each one performing separated tasks. I haven't tried it yet but for what I've seen the whole architecture idea seems great to me (it works the Unix way: one process, one task), but the project seems a little "green" yet. So, has anyone tried Shinken? What's your opinion?

    Read the article

  • Motherboard booting without RAM in Dimm1

    - by Jesus Ramos
    Is it possible to have a motherboard boot without placing RAM in the DIMM1 slot? Our new cooling solutions for motherboards are causing us issues where some boards that have RAM with raised heatsinks will not actually fit because the DIMM1 slot is partially blocked. Currently we mount the RAM in DIMM1 and DIMM3 because it's dual channel, are there any settings that can be changed on the BIOS to allow motherboard to boot without RAM in DIMM1 such as placing the RAM in DIMM2 and DIMM4?

    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

  • 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

  • Reconnoiter - Anyone using it?

    - by Marco Ramos
    Reconnoiter is a new tool in the world of monitoring. It is not only a trending tool but also alerting/fault detection one. In my particular case, I reckon that it's in the trending capacities that Reconnoiter has a very huge potential. One of the premises Recoinnoter is built upon is that RRDTool large installations are very inneficient regarding I/O and I think this is RRDTool major problem. One of the things that would make me change from Cacti is, obviously, the cost of change and the learning curve. So, any of you has experience with Reconnoiter? How's the learning curve? Was it difficult to move from RRDTool frontend applications (Cacti, Munin, Ganglia) to Reconnoiter? I'm looking forward to read your opinions.

    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

< Previous Page | 1 2 3 4 5 6  | Next Page >