Search Results

Search found 2526 results on 102 pages for 'peter st angelo'.

Page 7/102 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • One Exception to Aggregate Them All

    - by João Angelo
    .NET 4.0 introduced a new type of exception, the AggregateException which as the name implies allows to aggregate several exceptions inside a single throw-able exception instance. It is extensively used in the Task Parallel Library (TPL) and besides representing a simple collection of exceptions can also be used to represent a set of exceptions in a tree-like structure. Besides its InnerExceptions property which is a read-only collection of exceptions, the most relevant members of this new type are the methods Flatten and Handle. The former allows to flatten a tree hierarchy removing the need to recur while working with an aggregate exception. For example, if we would flatten the exception tree illustrated in the previous figure the result would be: The other method, Handle, accepts a predicate that is invoked for each aggregated exception and returns a boolean indicating if each exception is handled or not. If at least one exception goes unhandled then Handle throws a new AggregateException containing only the unhandled exceptions. The following code snippet illustrates this behavior and also another scenario where an aggregate exception proves useful – single threaded batch processing. static void Main() { try { ConvertAllToInt32("10", "x1x", "0", "II"); } catch (AggregateException errors) { // Contained exceptions are all FormatException // so Handle does not thrown any exception errors.Handle(e => e is FormatException); } try { ConvertAllToInt32("1", "1x", null, "-2", "#4"); } catch (AggregateException errors) { // Handle throws a new AggregateException containing // the exceptions for which the predicate failed. // In this case it will contain a single ArgumentNullException errors.Handle(e => e is FormatException); } } private static int[] ConvertAllToInt32(params string[] values) { var errors = new List<Exception>(); var integers = new List<int>(); foreach (var item in values) { try { integers.Add(Int32.Parse(item)); } catch (Exception e) { errors.Add(e); } } if (errors.Count > 0) throw new AggregateException(errors); return integers.ToArray(); }

    Read the article

  • We Don’t Need No Regions

    - by João Angelo
    If your code reaches a level where you want to hide it behind regions then you have a problem that regions won’t solve. Regions are good to hide things that you don’t want to have knowledge about such as auto-generated code. Normally, when you’re developing you end up reading more code than you write it so why would you want to complicate the reading process. I, for one, would love to have that one discussion around regions where someone convinces me that they solve a problem that has no other alternative solution, but I’m still waiting. The most frequent argument I hear about regions is that they allow you to structure your code, but why don’t just structure it using classes, methods and all that other stuff that OOP is about because at the end of the day, you should be doing object oriented programming and not region oriented programming. Having said that, I do believe that sometimes is helpful to have a quick overview of a code file contents and Visual Studio allows you to do just that through the Collapse to Definitions command (CTRL + M, CTRL + O) which collapses the members of all types; if you like regions, you should try this, it is much more useful to read all the members of a type than all the regions inside a type.

    Read the article

  • Razor – Hiding a Section in a Layout

    - by João Angelo
    Layouts in Razor allow you to define placeholders named sections where content pages may insert custom content much like the ContentPlaceHolder available in ASPX master pages. When you define a section in a Razor layout it’s possible to specify if the section must be defined in every content page using the layout or if its definition is optional allowing a page not to provide any content for that section. For the latter case, it’s also possible using the IsSectionDefined method to render default content when a page does not define the section. However if you ever require to hide a given section from all pages based on some runtime condition you might be tempted to conditionally define it in the layout much like in the following code snippet. if(condition) { @RenderSection("ConditionalSection", false) } With this code you’ll hit an error as soon as any content page provides content for the section which makes sense since if a page inherits a layout then it should only define sections that are also defined in it. To workaround this scenario you have a couple of options. Make the given section optional with and move the condition that enables or disables it to every content page. This leads to code duplication and future pages may forget to only define the section based on that same condition. The other option is to conditionally define the section in the layout page using the following hack: @{ if(condition) { @RenderSection("ConditionalSection", false) } else { RenderSection("ConditionalSection", false).WriteTo(TextWriter.Null); } } Hack inspired by a recent stackoverflow question.

    Read the article

  • VSTO Troubleshooting Quick Tips

    - by João Angelo
    If you ever find yourself troubleshooting a VSTO addin that does not load then these steps will interest you. Do not skip the basics and check the registry at HKLM\Software\Microsoft\Office\<Application>\AddIns\<AddInName> or HKCU\Software\Microsoft\Office\<Product>\AddIns\<Application> because if the LoadBehavior key is not set to 3 the office application will not even try to load it on startup; Enable error alerts popups by configuring an environment variable SET VSTO_SUPPRESSDISPLAYALERTS=0 Enable logging errors to file by configuring an environment variable SET VSTO_LOGALERTS=1 Pray for an error alert popup or for an error in the log file so that you can fix its cause.  

    Read the article

  • Code Trivia #5

    - by João Angelo
    A quick one inspired by real life broken code. What’s wrong in this piece of code? class Planet { public Planet() { this.Initialize(); } public Planet(string name) : this() { this.Name = name; } private string name = "Unspecified"; public string Name { get { return name; } set { name = value; } } private void Initialize() { Console.Write("Planet {0} initialized.", this.Name); } }

    Read the article

  • Extended Logging with Caller Info Attributes

    - by João Angelo
    .NET 4.5 caller info attributes may be one of those features that do not get much airtime, but nonetheless are a great addition to the framework. These attributes will allow you to programmatically access information about the caller of a given method, more specifically, the code file full path, the member name of the caller and the line number at which the method was called. They are implemented by taking advantage of C# 4.0 optional parameters and are a compile time feature so as an added bonus the returned member name is not affected by obfuscation. The main usage scenario will be for tracing and debugging routines as will see right now. In this sample code I’ll be using NLog, but the example is also applicable to other logging frameworks like log4net. First an helper class, without any dependencies and that can be used anywhere to obtain caller information: using System; using System.IO; using System.Runtime.CompilerServices; public sealed class CallerInfo { private CallerInfo(string filePath, string memberName, int lineNumber) { this.FilePath = filePath; this.MemberName = memberName; this.LineNumber = lineNumber; } public static CallerInfo Create( [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { return new CallerInfo(filePath, memberName, lineNumber); } public string FilePath { get; private set; } public string FileName { get { return this.fileName ?? (this.fileName = Path.GetFileName(this.FilePath)); } } public string MemberName { get; private set; } public int LineNumber { get; private set; } public override string ToString() { return string.Concat(this.FilePath, "|", this.MemberName, "|", this.LineNumber); } private string fileName; } Then an extension class specific for NLog Logger: using System; using System.Runtime.CompilerServices; using NLog; public static class LoggerExtensions { public static void TraceMemberEntry( this Logger logger, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { LogMemberEntry(logger, LogLevel.Trace, filePath, memberName, lineNumber); } public static void TraceMemberExit( this Logger logger, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { LogMemberExit(logger, LogLevel.Trace, filePath, memberName, lineNumber); } public static void DebugMemberEntry( this Logger logger, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { LogMemberEntry(logger, LogLevel.Debug, filePath, memberName, lineNumber); } public static void DebugMemberExit( this Logger logger, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { LogMemberExit(logger, LogLevel.Debug, filePath, memberName, lineNumber); } public static void LogMemberEntry( this Logger logger, LogLevel logLevel, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { const string MsgFormat = "Entering member {1} at line {2}"; InternalLog(logger, logLevel, MsgFormat, filePath, memberName, lineNumber); } public static void LogMemberExit( this Logger logger, LogLevel logLevel, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { const string MsgFormat = "Exiting member {1} at line {2}"; InternalLog(logger, logLevel, MsgFormat, filePath, memberName, lineNumber); } private static void InternalLog( Logger logger, LogLevel logLevel, string format, string filePath, string memberName, int lineNumber) { if (logger == null) throw new ArgumentNullException("logger"); if (logLevel == null) throw new ArgumentNullException("logLevel"); logger.Log(logLevel, format, filePath, memberName, lineNumber); } } Finally an usage example: using NLog; internal static class Program { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static void Main(string[] args) { Logger.TraceMemberEntry(); // Compile time feature // Next three lines output the same except for line number Logger.Trace(CallerInfo.Create().ToString()); Logger.Trace(() => CallerInfo.Create().ToString()); Logger.Trace(delegate() { return CallerInfo.Create().ToString(); }); Logger.TraceMemberExit(); } } NOTE: Code for helper class and Logger extension also available here.

    Read the article

  • VS 2010 SP1 BETA – App.config XML Transformation Fix

    - by João Angelo
    The current version for App.config XML tranformations as described in a previous post does not support the SP1 BETA version of Visual Studio. I did some quick tests and decided to provide a different version with a compatibility fix for those already experimenting with the beta release of the service pack. This is a quick workaround to the build errors I found when using the transformations in SP1 beta and is pretty much untested since I’ll wait for the final release of the service pack to take a closer look to any possible problems. But for now, those that already installed SP1 beta can use the following transformations: VS 2010 SP1 BETA – App.config XML Transformation And those with the RTM release of Visual Studio can continue to use the original version of the transformations available from: VS 2010 RTM – App.config XML Transformation

    Read the article

  • The internal storage of a DATETIME2 value

    - by Peter Larsson
    Today I went for investigating the internal storage of DATETIME2 datatype. What I found out was that for a datetime2 value with precision 0 (seconds only), SQL Server need 6 bytes to represent the value, but stores 7 bytes. This is because SQL Server add one byte that holds the precision for the datetime2 value. Start with this very simple repro declare @now datetime2(7) = '2010-12-15 21:04:03.6934231'   select  cast(cast(@now as datetime2(0)) as binary(7)),         cast(cast(@now as datetime2(1)) as binary(7)),         cast(cast(@now as datetime2(2)) as binary(7)),         cast(cast(@now as datetime2(3)) as binary(8)),         cast(cast(@now as datetime2(4)) as binary(8)),         cast(cast(@now as datetime2(5)) as binary(9)),         cast(cast(@now as datetime2(6)) as binary(9)),         cast(cast(@now as datetime2(7)) as binary(9)) Now we are going to copy and paste these binary values and investigate which value is representing what time part. Prefix  Ticks       Ticks         Days    Days    Original value ------  ----------  ------------  ------  ------  -------------------- 0x  00  442801             75844  A8330B  734120  0x00442801A8330B 0x  01  A5920B            758437  A8330B  734120  0x01A5920BA8330B  0x  02  71BA73           7584369  A8330B  734120  0x0271BA73A8330B 0x  03  6D488504        75843693  A8330B  734120  0x036D488504A8330B 0x  04  46D4342D       758436934  A8330B  734120  0x0446D4342DA8330B 0x  05  BE4A10C401    7584369342  A8330B  734120  0x05BE4A10C401A8330B 0x  06  6FEBA2A811   75843693423  A8330B  734120  0x066FEBA2A811A8330B 0x  07  57325D96B0  758436934231  A8330B  734120  0x0757325D96B0A8330B Let us use the following color schema Red - Prefix Green - Time part Blue - Day part What you can see is that the date part is equal in all cases, which makes sense since the precision doesm't affect the datepart. What would have been fun, is datetime2(negative) just like round accepts a negative value. -1 would mean rounding to 10 second, -2 rounding to minute, -3 rounding to 10 minutes, -4 rounding to hour and finally -5 rounding to 10 hour. -5 is pretty useless, but if you extend this thinking to -6, -7 and so on, you could actually get a datetime2 value which is accurate to the month only. Well, enough ranting about this. Let's get back to the table above. If you add 75844 second to midnight, you get 21:04:04, which is exactly what you got in the select statement above. And if you look at it, it makes perfect sense that each following value is 10 times greater when the precision is increased one step too. //Peter

    Read the article

  • Don’t Program by Fear, Question Everything

    - by João Angelo
    Perusing some code base I’ve recently came across with a code comment that I would like to share. It was something like this: class Animal { public Animal() { this.Id = Guid.NewGuid(); } public Guid Id { get; private set; } } class Cat : Animal { public Cat() : base() // Always call base since it's not always done automatically { } } Note: All class names were changed to protect the innocent. To clear any possible doubts the C# specification explicitly states that: If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided. Thus, an instance constructor declaration of the form C(...) {...} is exactly equivalent to C(...): base() {...} So in conclusion it’s clearly an incorrect comment but what I find alarming is how a comment like that gets into a code base and survives the test of time. Not to forget what it can do to someone who is making a jump from other technologies to C# and reads stuff like that.

    Read the article

  • Code Trivia #4

    - by João Angelo
    Got the inspiration for this one in a recent stackoverflow question. What should the following code output and why? class Program { class Author { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return LastName + ", " + FirstName; } } static void Main() { Author[] authors = new[] { new Author { FirstName = "John", LastName = "Doe" }, new Author { FirstName = "Jane", LastName="Doe" } }; var line1 = String.Format("Authors: {0} and {1}", authors); Console.WriteLine(line1); string[] serial = new string[] { "AG27H", "6GHW9" }; var line2 = String.Format("Serial: {0}-{1}", serial); Console.WriteLine(line2); int[] version = new int[] { 1, 0 }; var line3 = String.Format("Version: {0}.{1}", version); Console.WriteLine(line3); } } Update: The code will print the first two lines // Authors: Doe, John and Doe, Jane // Serial: AG27H-6GHW9 and then throw an exception on the third call to String.Format because array covariance is not supported in value types. Given this the third call of String.Format will not resolve to String.Format(string, params object[]), like the previous two, but to String.Format(string, object) which fails to provide the second argument for the specified format and will then cause the exception.

    Read the article

  • SPARC M7 Chip - 32 cores - Mind Blowing performance

    - by Angelo-Oracle
    The M7 Chip Oracle just announced its Next Generation Processor at the HotChips HC26 conference. As the Tech Lead in our Systems Division's Partner group, I had a front row seat to the extraordinary price performance advantage of Oracle current T5 and M6 based systems. Partner after partner tested  these systems and were impressed with it performance. Just read some of the quotes to see what our partner has been saying about our hardware. We just announced our next generation processor, the M7. This has 32 cores (up from 16-cores in T5 and 12-cores in M6). With 20 nm technology  this is our most advanced processor. The processor has more cores than anything else in the industry today. After the Sun acquisition Oracle has released 5 processors in 4 years and this is the 6th.  The S4 core  The M7 is built using the foundation of the S4 core. This is the next generation core technology. Like its predecessor, the S4 has 8 dynamic threads. It increases the frequency while maintaining the Pipeline depth. Each core has its own fine grain power estimator that keeps the core within its power envelop in 250 nano-sec granularity. Each core also includes Software in Silicon features for Application Acceleration Support. Each core includes features to improve Application Data Integrity, with almost no performance loss. The core also allows using part of the Virtual Address to store meta-data.  User-Level Synchronization Instructions are also part of the S4 core. Each core has 16 KB Instruction and 16 KB Data L1 cache. The Core Clusters  The cores on the M7 chip are organized in sets of 4-core clusters. The core clusters share  L2 cache.  All four cores in the complex share 256 KB of 4 way set associative L2 Instruction Cache, with over 1/2 TB/s of throughput. Two cores share 256 KB of 8 way set associative L2 Data Cache, with over 1/2 TB/s of throughput. With this innovative Core Cluster architecture, the M7 doubles core execution bandwidth. to maximize per-thread performance.  The Chip  Each  M7 chip has 8 sets of these core-clusters. The chip has 64 MB on-chip L3 cache. This L3 caches is shared among all the cores and is partitioned into 8 x 8 MB chunks. Each chunk is  8-way set associative cache. The aggregate bandwidth for the L3 cache on the chip is over 1.6TB/s. Each chip has 4 DDR4 memory controllers and can support upto 16 DDR4 DIMMs, allowing for 2 TB of RAM/chip. The chip also includes 4 internal links of PCIe Gen3 I/O controllers.  Each chip has 7 coherence links, allowing for 8 of these chips to be connected together gluelessly. Also 32 of these chips can be connected in an SMP configuration. A potential system with 32 chips will have 1024 cores and 8192 threads and 64 TB of RAM.  Software in Silicon The M7 chip has many built in Application Accelerators in Silicon. These features will be exposed to our Software partners using the SPARC Accelerator Program.  The M7  has built-in logic to decompress data at the speed of memory access. This means that applications can directly work on compressed data in memory increasing the data access rates. The VA Masking feature allows the use of part of the virtual address to store meta-data.  Realtime Application Data Integrity The Realtime Application Data Integrity feature helps applications safeguard against invalid, stale memory reference and buffer overflows. The first 4-bits if the Pointer can be used to store a version number and this version number is also maintained in the memory & cache lines. When a pointer accesses memory the hardware checks to make sure the two versions match. A SEGV signal is raised when there is a mismatch. This feature can be used by the Database, applications and the OS.  M7 Database In-Memory Query Accelerator The M7 chip also includes a In-Silicon Query Engines.  These accelerate tasks that work on In-Memory Columnar Vectors. Oracle In-Memory options stores data in Column Format. The M7 Query Engine can speed up In-Memory Format Conversion, Value and Range Comparisons and Set Membership lookups. This engine can work on Compressed data - this means not only are we accelerating the query performance but also increasing the memory bandwidth for queries.  SPARC Accelerated Program  At the Hotchips conference we also introduced the SPARC Accelerated Program to provide our partners and third part developers access to all the goodness of the M7's SPARC Application Acceleration features. Please get in touch with us if you are interested in knowing more about this program. 

    Read the article

  • Does not recognize usb sticks and drives

    - by Peter
    When connecting any usb stick to my thinkpad ubuntu 10.10 does not recognize them. I don't see anything on the desktop. the output of "dmesg | tail -n10" gives me: [ 1965.696388] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1965.884537] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.072503] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.260349] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.506227] usb 1-1: new high speed USB device using ehci_hcd and address 9 [ 1966.572375] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.760379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.948358] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.136335] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.325423] hub 1-0:1.0: unable to enumerate USB device on port 1 When connecting my usb scanner to the same port: [ 2008.480135] usb 1-1: new high speed USB device using ehci_hcd and address 65 [ 2008.548389] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.736786] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.924379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.112348] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.300443] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.488536] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.732180] usb 1-1: new high speed USB device using ehci_hcd and address 71 [ 2014.796299] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2018.000128] usb 2-1: new full speed USB device using uhci_hcd and address 3 And ubuntu 10.10 recognizes that scanner. So: What can i do to see my usb stick? BTW: on my other Thinkpad running fedora 14 it works perfectly... Cheers -Peter

    Read the article

  • 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

  • Purging SOA Instances

    - by angelo.santagata
    All, If your running Oracle SOA suite in a high thoughput environment you'll probably discover that your dehydration store will get large, and larger if you dont manage it properly. There are many strategies in manging how to purge this, and this document recently released by Oracle details them quite nicely. The document is Oracle SOA Suite 10g based however a 11g version is in the works and should be out soon. Enjoy the read

    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

  • 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

  • Weblogic 10.3.4 (PS3) nodemanager wont start?

    - by angelo.santagata
    Hi all, well Im back from Australia and one of the things which happened was Oracle announced the PS3 release of oracles SOA & Webcenter products have been released. Now I normally use pre-installed images but I always like to install the products at least once that way I get to see its installation caveats.. Here’s one. Installation on Windows 7 64bit, 64bit JVM, generic weblogic Server installer. All worked fine, EXCEPT I cant start the node manager, I get the following error <08-Feb-2011 17:16:48> <INFO> <Loading domains file: D:\products\wls1034\WLSERV~1.3\common\NODEMA~1\nodemanager.domains> <08-Feb-2011 17:16:48> <SEVERE> <Fatal error in node manager server> weblogic.nodemanager.common.ConfigException: Native version is enabled but nodemanager native library could not be loaded     at weblogic.nodemanager.server.NMServerConfig.initProcessControl(NMServerConfig.java:249)     at weblogic.nodemanager.server.NMServerConfig.<init>(NMServerConfig.java:190)     at weblogic.nodemanager.server.NMServer.init(NMServer.java:182)     at weblogic.nodemanager.server.NMServer.<init>(NMServer.java:148)     at weblogic.nodemanager.server.NMServer.main(NMServer.java:390)     at weblogic.NodeManager.main(NodeManager.java:31) Caused by: java.lang.UnsatisfiedLinkError: D:\products\wls1034\wlserver_10.3\server\native\win\32\nodemanager.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform     at java.lang.ClassLoader$NativeLibrary.load(Native Method)     at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1803)     at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1728)     at java.lang.Runtime.loadLibrary0(Runtime.java:823)     at java.lang.System.loadLibrary(System.java:1028)     at weblogic.nodemanager.util.WindowsProcessControl.<init>(WindowsProcessControl.java:17)     at weblogic.nodemanager.util.ProcessControlFactory.getProcessControl(ProcessControlFactory.java:24)     at weblogic.nodemanager.server.NMServerConfig.initProcessControl(NMServerConfig.java:247)     ... 5 more Ok it appears that the node manager has gotten confused and thinks this is a 32bit install of Weblogic Server whereas it is the 64bit install.. Might have been something I did, or didnt do, on installation (e.g. –d64 on the jvm command line), however the workaround is pretty easy. 1. Create a file called nodemanager.properties in %WL_HOME%\common\nodemanager on my machine it was D:\products\wls1034\wlserver_10.3\common\nodemanager 2. Add the following line to it NativeVersionEnabled=false 3. And start it up!, this will force it not to use .DLL files and use emulation/non native methods instead..  

    Read the article

  • My first encounter with SmartAssembly

    - by Peter Larsson
    Let me start by writing I am a supreme VB6 programmer, but I have very little experience with VB.Net, so I think I still need some more time learning SmartAssembly. SmartAssembly make obfuscating and merging dll files a piece of cake! With it's simple, straight forward and clean GUI I did make my tests work. With other obfuscators like Xenocode, Salamander etc which lets you (and in some cases forces you) control more advanced settings, you really have to know what you are doing. Especially when it comes to protecting code that uses external dependencies. My most annoying experience is that if you start checking radio buttons and activating different obfuscating features in SmartAssembly, you will end up breaking your working code as well, if you like me is not that experienced and don't know what you’re doing. SmartAssembly have some troubleshooting information on their website which explains why the application will fail in some scenarios. So why not extend these checks in some deeper analyzing stage on the dll's? By doing that I think more people could get fully functional dll's out of the box instead of trying different settings and then test the protected dll and see if it's working or not. //Peter

    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

  • Webcenter and accessability

    - by angelo.santagata
    Got asked about webcenter accessability today, and the answer is obsolutely yes Oracle WebCenter 11gR1 has been tested against Oracle's Accessibility Guidelines (OGHAG), that combine guidelines of Section 508 and WCAG 1.0 'AA'. Here are the links to the product VPATs: VPAT for WebCenter Framework 11gR1: http://www.oracle.com/accessibility/templates/t1008.html VPAT for WebCenter Spaces 11gR1: http://www.oracle.com/accessibility/templates/t1684.html WebCenter 11gR1 PS1 has been tested against the current iteration of OGHAG, that factors in WCAG 2.0.

    Read the article

  • What version of webcenter do I have?

    - by angelo.santagata
    Ive seen this come up a few times, someone has webcenter installed, but isnt sure *exactly* which version of webcenter 11g they have installed.. Well its quite easy... Connect to sqplus as SYSDBA to the WebCenter database Run the following query to get the WebCenter schema: select username from all_users where username like '%WEBCENTER%'; Take note of the WebCenter username so you can use in next query. Run the following query to get the WebCenter version: Replace: - With the username from previous query. select version from .WC_REPOSITORY_VERSION; Also worth noting this is all documented in support note Note 1053606.1 available at metalink

    Read the article

  • ubuntu 10.10 does not recognize usb sticks and drives

    - by Peter
    When connecting any usb stick to my thinkpad ubuntu 10.10 does not recognize them. I don't see anything on the desktop. the output of "dmesg | tail -n10" gives me: [ 1965.696388] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1965.884537] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.072503] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.260349] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.506227] usb 1-1: new high speed USB device using ehci_hcd and address 9 [ 1966.572375] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.760379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1966.948358] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.136335] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 1967.325423] hub 1-0:1.0: unable to enumerate USB device on port 1 When connecting my usb scanner to the same port: [ 2008.480135] usb 1-1: new high speed USB device using ehci_hcd and address 65 [ 2008.548389] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.736786] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2008.924379] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.112348] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.300443] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.488536] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2009.732180] usb 1-1: new high speed USB device using ehci_hcd and address 71 [ 2014.796299] hub 1-0:1.0: unable to enumerate USB device on port 1 [ 2018.000128] usb 2-1: new full speed USB device using uhci_hcd and address 3 And ubuntu 10.10 recognizes that scanner. So: What can i do to see my usb stick? BTW: on my other Thinkpad running fedora 14 it works perfectly... Cheers -Peter

    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

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >