Search Results

Search found 1306 results on 53 pages for 'eric huang'.

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

  • TreeMap sort by value

    - by vito huang
    I'm new to java, i want to write an comparator to that will let me sort TreeMap by value instead of the default natural sorting. i tried something like this, but can't find out what went wrong: import java.util.*; class treeMap { public static void main(String[] args) { System.out.println("the main"); byValue cmp = new byValue(); Map<String, Integer> map = new TreeMap<String, Integer>(cmp); map.put("de",10); map.put("ab", 20); map.put("a",5); for (Map.Entry<String,Integer> pair: map.entrySet()) { System.out.println(pair.getKey()+":"+pair.getValue()); } } } class byValue implements Comparator<Map.Entry<String,Integer>> { public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) { if (e1.getValue() < e2.getValue()){ return 1; } else if (e1.getValue() == e2.getValue()) { return 0; } else { return -1; } } } I guess what am i asking is what controls what get pass to comparator function, can i get an Map.Entry pass to comparator?

    Read the article

  • How should I format an HTTPService result in Flex so that it is accessible for a pie chart?

    - by Eric Reynolds
    I feel like this should be simple, however everywhere I look online someone does something different. I am doing a small charting application to track download statistics, and want to put the data into a pie chart. I am new to Flex, so if my code is horrible I apologize. <s:HTTPService id="service" url="admin/stats/totalstats.php" fault="service_faultHandler(event)" result="service_resultHandler(event)" /> What is the best resultFormat for this purpose, and if I am assigning the returned value to an ActionScript variable, should it be an ArrayList? ArrayCollection? Heres a sample of the XML being returned from the HTTPService <DownloadStats> <year count="24522" year="2008"> <month count="20" month="5" year="2008" full="May 2008"> <day count="2" month="5" day="20" year="2008"/> <day count="1" month="5" day="21" year="2008"/> <day count="9" month="5" day="22" year="2008"/> <day count="1" month="5" day="23" year="2008"/> <day count="1" month="5" day="29" year="2008"/> <day count="1" month="5" day="30" year="2008"/> <day count="5" month="5" day="31" year="2008"/> </month> ... </year> <DownloadStats> Any help is appreciated, Thanks, Eric R. EDIT: I decided that it would be helpful to see how I am transferring the data to the chart to make sure I am not doing something wrong there either. <mx:PieChart id="pieChart"> <mx:PieSeries nameField="year" field="count" labelPosition="callout" displayName="Total" dataProvider="{graphData}"/> </mx:PieChart>

    Read the article

  • Center a TextBox over the top of a ScrollViewer in WPF.

    - by Eric
    I have a MainView that contains a navigation bar which selects one of many XAML pages to be displayed in the page view pane. The MainView contains a ScrollViewer around the pages. This allows the pages to be whatever size they need to be and the MainView's ScrollViewer scrolls them. This all works great. On one of the pages, I need to (sometimes) center a TextBox in the middle of the page view pane (over the top of the page content). This was easily done by placing both the page content and the TextBox overlapping each other in a Grid (and I hide the TextBox as necessary). This all seems to work great. However, if the page content grows to be larger than the pane, the TextBox is centered not on the pane, but on the full page content. Thus, it moves from center screen down and/or to the right (and eventually off the screen). Bummer. Options: Remove the ScrollViewer from the MainView. This would require placing one on every page! Argh. Do option #1, and create a ScrolledPage base class. This is a lot of work, and I'm worried about tools issues (Blend issues). It also requires changing every page (to subclass this page). Somehow override the ScrollViewer on just this page. Then, place another ScrollViewer on the page content to Scroll it. Option 3 seems preferable, because it contains the issue to just modifying this page (instead of changing the rest of the pages). However, I can't figure out how to do it. Ideas? Thanks in advance! Eric

    Read the article

  • Can I un-check a group of RadioBottoms inside a group box?

    - by Claire Huang
    radio bottoms inside a group Box will be treated as a group of bottoms. They are mutual exclusive. How can I clean up their check states?? I have several radio bottoms, one of them are checked. How can I "clean" (uncheck) all radio bottoms?? "setChecked" doesn't work within a group, I tried to do following things but failed. My code is as following, radioButtom is inside a groupBox, and I want to unchecked it. The first setChecked does works, but the second one doesn't, the radioBottom doesn't been unchecked MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { QRadioButton *radioButton; ui->setupUi(this); radioButton->setChecked(true); radioButton->setChecked(false); } Where is the problem in my code?

    Read the article

  • Valgrind 'noise', what does it mean?

    - by Chris Huang-Leaver
    When I used valgrind to help debug an app I was working on I notice a huge about of noise which seems to be complaining about standard libraries. As a test I did this; echo 'int main() {return 0;}' | gcc -x c -o test - Then I did this; valgrind ./test ==1096== Use of uninitialised value of size 8 ==1096== at 0x400A202: _dl_new_object (in /lib64/ld-2.10.1.so) ==1096== by 0x400607F: _dl_map_object_from_fd (in /lib64/ld-2.10.1.so) ==1096== by 0x4007A2C: _dl_map_object (in /lib64/ld-2.10.1.so) ==1096== by 0x400199A: map_doit (in /lib64/ld-2.10.1.so) ==1096== by 0x400D495: _dl_catch_error (in /lib64/ld-2.10.1.so) ==1096== by 0x400189E: do_preload (in /lib64/ld-2.10.1.so) ==1096== by 0x4003CCD: dl_main (in /lib64/ld-2.10.1.so) ==1096== by 0x401404B: _dl_sysdep_start (in /lib64/ld-2.10.1.so) ==1096== by 0x4001471: _dl_start (in /lib64/ld-2.10.1.so) ==1096== by 0x4000BA7: (within /lib64/ld-2.10.1.so) * large block of similar snipped * ==1096== Use of uninitialised value of size 8 ==1096== at 0x4F35FDD: (within /lib64/libc-2.10.1.so) ==1096== by 0x4F35B11: (within /lib64/libc-2.10.1.so) ==1096== by 0x4A1E61C: _vgnU_freeres (vg_preloaded.c:60) ==1096== by 0x4E5F2E4: __run_exit_handlers (in /lib64/libc-2.10.1.so) ==1096== by 0x4E5F354: exit (in /lib64/libc-2.10.1.so) ==1096== by 0x4E48A2C: (below main) (in /lib64/libc-2.10.1.so) ==1096== ==1096== ERROR SUMMARY: 3819 errors from 298 contexts (suppressed: 876 from 4) ==1096== malloc/free: in use at exit: 0 bytes in 0 blocks. ==1096== malloc/free: 0 allocs, 0 frees, 0 bytes allocated. ==1096== For counts of detected errors, rerun with: -v ==1096== Use --track-origins=yes to see where uninitialised values come from ==1096== All heap blocks were freed -- no leaks are possible. You can see the full result here: http://pastebin.com/gcTN8xGp I have two questions; firstly is there a way to suppress all the noise? --show-below-main is set to no by default, but there doesn't appear to be a --show-after-main equivalent.

    Read the article

  • why the main method are not covered? urgent, please help me

    - by Mike.Huang
    main method: public static void main(String[] args) throws Exception { if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS) { System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR"); } String configXML = args[0]; String packageXML = args[1]; String xfr = args[2]; AutoConfigCompiler compiler = new AutoConfigCompiler(); compiler.setConfigDocument(loadDocument(configXML)); compiler.setPackageInfoDoc(loadDocument(packageXML)); // compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml")); compiler.compileModel(xfr); } private static Document loadDocument(String fileName) throws Exception { TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName()); InputSource source = new InputSource(new FileInputStream(fileName)); parser.parse(source); return parser.getDocument(); } testcase: @Test public void testCompileModel() throws Exception { // construct parameters URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml"); URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml"); File tmpFile = new File("Ford_2008_Mustang_tmp.xfr"); if(!tmpFile.exists()) { tmpFile.createNewFile(); } String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()}; try { // test main method XFRCompiler.main(args); } catch (Exception e) { assertTrue(true); } try { // test args length is less than 3 XFRCompiler.main(new String[]{"",""}); } catch (Exception e) { assertTrue(true); } tmpFile.delete(); } coverage outputs displayed as the lines from “String configXML = args[0];" in main method are not covered

    Read the article

  • Is there a way to get the PREMATCH ($`) and POSTMATCH ($') from pcrecpp?

    - by Eric Peers
    Is there a way to obtain the C++ equivalent of Perl's PREMATCH ($`) and POSTMATCH ($') from pcrecpp? I would be happy with a string, a char *, or pairs indices/startpos+length that point at this. StringPiece seems like it might accomplish part of this, but I'm not certain how to get it. in perl: $_ = "Hello world"; if (/lo\s/) { $pre = $`; #should be "Hel" $post = $'; #should be "world" } in C++ I would have something like: string mystr = "Hello world"; //do I need to map this in a StringPiece? if (pcrecpp::RE("lo\s").PartialMatch(mystr)) { //should I use Consume or FindAndConsume? //What should I do here to get pre+post matches??? } pcre plainjane c seems to have the ability to return the vector with the matches including the "end" portion of the string, so I could theoretically extract such a pre/post variable, but that seems like a lot of work. I like the simplicty of the pcrecpp interface. Suggestions? Thanks! --Eric

    Read the article

  • the characters except 0x00-0x7F are not been shown when converted to "UTF-8" from "ISO-8859-1"

    - by Mike.Huang
    I need to get a string from URL request of brower, and then create a text image by requested text. I know the default encoding of the Java net transmission is "ISO-8859-1", it can works normally with all characters what defined in "ISO-8859-1". But when I request a multi-byte Unicode character (e.g. chinese or something like ¤?), then I need to decode it by "UTF-8" from "ISO-8859-1". My codes like: String reslut = new String(requestString.getBytes("ISO-8859-1"), "UTF-8"); Everything is fine, but I found some characters in ISO-8859-1 are not been shown now, which characters are 0x80 - 0xFF(defined in" ISO-8859-1"), i.e. the characters except 0x00-0x7F are not been shown when converted to "UTF-8" from "ISO-8859-1" Any other method can solve this query?

    Read the article

  • Is using .h as a header for a c++ file wrong?

    - by Chris Huang-Leaver
    Is using .h as a header for a c++ file wrong? I see it all over the place, especially with code written in the "C style". I noticed that Emacs always selects C highlighting style for a .h header, but c++ for hpp or hh. Is it actually "wrong" to label your headers .h or is it just something which annoys me? EDIT: There is a good (ish) reason why this annoys me, if I have project files labelled, 'hpp & cpp' I can get away with 'grep something *pp' etc. otherwise I have to type '.h cpp'

    Read the article

  • Why is the main method not covered?

    - by Mike.Huang
    main method: public static void main(String[] args) throws Exception { if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS) { System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR"); } String configXML = args[0]; String packageXML = args[1]; String xfr = args[2]; AutoConfigCompiler compiler = new AutoConfigCompiler(); compiler.setConfigDocument(loadDocument(configXML)); compiler.setPackageInfoDoc(loadDocument(packageXML)); // compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml")); compiler.compileModel(xfr); } private static Document loadDocument(String fileName) throws Exception { TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName()); InputSource source = new InputSource(new FileInputStream(fileName)); parser.parse(source); return parser.getDocument(); } testcase: @Test public void testCompileModel() throws Exception { // construct parameters URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml"); URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml"); File tmpFile = new File("Ford_2008_Mustang_tmp.xfr"); if(!tmpFile.exists()) { tmpFile.createNewFile(); } String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()}; try { // test main method XFRCompiler.main(args); } catch (Exception e) { assertTrue(true); } try { // test args length is less than 3 XFRCompiler.main(new String[]{"",""}); } catch (Exception e) { assertTrue(true); } tmpFile.delete(); } Coverage outputs displayed as the lines from String configXML = args[0]; in main method are not covered.

    Read the article

  • GPG error occurs while using "deb file:/local-path-to-repo ..." in /etc/apt/sources.list

    - by Chandler.Huang
    I need to install packages within non-internet connection environment. My plan is to download dist structure from Internet and then add file path to /etc/apt/sources.list. So I download related structure includes ubunt/dists/precise, precise-backports, precise-proposed, precise-security, precise-updates from a ftp mirror server. And then I remove original source and add the following to my /etc/apt/sources.list. deb file:path-to-local-ubuntu-directory/ precise main restricted multiverse universe deb-src file:path-to-local-ubuntu-directory/ precise main restricted multiverse universe Then I got GPG error as following after apt-get update. root@openstack:/~# apt-get update Ign file: precise InRelease Get:1 file: precise Release.gpg [198 B] Get:2 file: precise Release [50.1 kB] Ign file: precise Release Get:3 file: precise/main TranslationIndex [3,761 B] Get:4 file: precise/multiverse TranslationIndex [2,716 B] Get:5 file: precise/restricted TranslationIndex [2,636 B] Get:6 file: precise/universe TranslationIndex [2,965 B] Reading package lists... Done W: GPG error: file: precise Release: The following signatures were invalid: BADSIG 0976EAF437D05B5 Ubuntu Archive Automatic Signing Key <[email protected]> I had tried use the following steps after google but in vain. sudo apt-get clean cd /var/lib/apt sudo mv lists lists.old sudo mkdir -p lists/partial sudo apt-get update Is there any way to resolve this? And why this error occurs? Thanks a lot.

    Read the article

  • MTD Expression on a single column - SSRS

    - by Eric
    I need a bit of help here. I have been unable to create an 'Month To Date' expression to a single column on SSRS. I tested the following expression from a similar question in the forum, but it gives me a squiggly line below the variable 'd' =IIF(Fields!CreateDate.Value >= DateAdd(d,-7,Today()), Sum(Fields!Sales.Value), 0) If I run it, of course I got an error telling me that 'd' is not declared. ;) I changed it to ... DateAdd("d",-7,Today()), Sum(Fields!Sales.Value) ... following the example and the squiggly goes below the brackets of "today()" and needless to say it...but still not working. I tried a Dateadd(mm..Datediff ... and still nothing. My report has the following columns: Country | CustomerName | Sales | InvNotProcessed | Open Order | Orders | TotalbyCust What I need is to show the new MTD sales only in the column named "Sales" while the other three shows the rest of the query, which should be open as some orders may take quite a while to manufacture and invoice. the last column sums the totals of all other columns. Any help will be much appreciated. Regards, Eric

    Read the article

  • Inspire Geek Love with These Hilarious Geek Valentines

    - by Eric Z Goodnight
    Want to send some Geek Love to that special someone? Why not do it with these elementary school throwback valentines, and win their heart this upcoming Valentine’s day—the geek way! Read on to see the simple method to make your own custom Valentines, as well as download a set of eleven ready-made ones any geek guy or gal should be delighted get. It’s amore! How to Make Custom Valentines A size we’ve used for all of our Valentines is a 3” x 4” at 150 dpi. This is fairly low resolution for print, but makes a great graphic to email. With your new image open, Navigate to Edit > Fill and fill your background layer with a rich, red color (or whatever appeals to you.) By setting “Use” to “Foreground color as shown above, you’ll paint whatever foreground color you have in your color picker. Press to select the text tool. Set a few text objects, using whatever fonts appeal to you. Pixel fonts, like this one, are freely downloadable, and we’ve already shared a great list of Valentines fonts. Copy an image from the internet if you’re confident your sweetie won’t mind a bit of fair use of copyrighted imagery. If they do mind, find yourself some great Creative Commons images. to do a free transform on your image, sizing it to whatever dimensions work best for your design. Right click your newly added image layer in your panel and Choose “Blending Effects” to pick a Layer Style. “Stroke” with this setting adds a black line around your image. Also turning on “Outer Glow” with this setting puts a dark black shadow around the top and bottom (and sides, although they are hidden). Add some more text. Double entendre is recommended. Click and hold down on the “Rectangle Tool” to get the “Custom Shape Tool.” The custom shape tool has useful vector shapes built into it. Find the “Shape” dropdown in the menu to find the heart image. Click and drag to create a vector heart shape in your image. Your layers panel is where you can change the color, if it happens to use the wrong one at first. Click the color swatch in your panel, highlighted in blue above. will transform your vector heart. You can also use it to rotate, if you like. Add some details, like this Power or Standby symbol, which can be found in symbol fonts, taken from images online, or drawn by hand. Your Valentine is now ready to be saved as a JPG or PNG and sent to the object of your affection! Keep reading to see a list of 11 downloadable How-To Geek Valentines, including this one and the three from the header image. Download The HTG Set of Valentines Download the HTG Geek Valentines (ZIP) Download the HTG Geek Valentines (ZIP) When he’s not wooing ladies with Valentines cards, you can email the author at [email protected] with your Photoshop and Graphics questions. Your questions may be featured in a future How-To Geek article! Latest Features How-To Geek ETC Inspire Geek Love with These Hilarious Geek Valentines How to Integrate Dropbox with Pages, Keynote, and Numbers on iPad RGB? CMYK? Alpha? What Are Image Channels and What Do They Mean? How to Recover that Photo, Picture or File You Deleted Accidentally How To Colorize Black and White Vintage Photographs in Photoshop How To Get SSH Command-Line Access to Windows 7 Using Cygwin How to Kid Proof Your Computer’s Power and Reset Buttons Microsoft’s Windows Media Player Extension Adds H.264 Support Back to Google Chrome Android Notifier Pushes Android Notices to Your Desktop Dead Space 2 Theme for Chrome and Iron Carl Sagan and Halo Reach Mashup – We Humans are Capable of Greatness [Video] Battle the Necromorphs Once Again on Your Desktop with the Dead Space 2 Theme for Windows 7

    Read the article

  • Q&amp;A: Can you develop for the Windows Azure Platform using Windows XP?

    - by Eric Nelson
    This question has come up several times recently as we take several hundred UK developers through 6 Weeks of Windows Azure training (sorry – we are full). Short answer: In the main, yes Longer answer: The question is sparked by the requirements as stated on the Windows Azure SDK download page. Namely: Supported Operating Systems: Windows 7; Windows Vista; Windows Vista 64-bit Editions Service Pack 1; Windows Vista Business; Windows Vista Business 64-bit edition; Windows Vista Enterprise; Windows Vista Enterprise 64-bit edition; Windows Vista Home Premium; Windows Vista Home Premium 64-bit edition; Windows Vista Service Pack 1; Windows Vista Service Pack 2; Windows Vista Ultimate; Windows Vista Ultimate 64-bit edition Notice there is no mention of Windows XP. However things are not quite that simple. The Windows Azure Platform consists of three released technologies Windows Azure SQL Azure Windows Azure platform AppFabric The Windows Azure SDK is only for one of the three technologies, Windows Azure. What about SQL Azure and AppFabric? Well it turns out that you can develop for both of these technologies just fine with Windows XP: SQL Azure development is really just SQL Server development with a few gotchas – and for local development you can simply use SQL Server 2008 R2 Express (other versions will also work). AppFabric also has no local simulation environment and the SDK will install fine on Windows XP (SDK download) Actually it is also possible to do Windows Azure development on Windows XP if you are willing to always work directly against the real Azure cloud running in Microsoft datacentres. However in practice this would be painful and time consuming, hence why the Windows Azure SDK installs a local simulation environment. Therefore if you want to develop for Windows Azure I would recommend you either upgrade from Windows XP to Windows 7 or… you use a virtual machine running Windows 7. If this is a temporary requirement, then you could consider building a virtual machine using the Windows 7 Enterprise 90 day eval. Or you could download a pre-configured VHD – but I can’t quite find the link for a Windows 7 VHD. Pointers welcomed. Thanks.

    Read the article

  • GuestPost: Unit Testing Entity Framework (v1) Dependent Code using TypeMock Isolator

    - by Eric Nelson
    Time for another guest post (check out others in the series), this time bringing together the world of mocking with the world of Entity Framework. A big thanks to Moses for agreeing to do this. Unit Testing Entity Framework Dependent Code using TypeMock Isolator by Muhammad Mosa Introduction Unit testing data access code in my opinion is a challenging thing. Let us consider unit tests and integration tests. In integration tests you are allowed to have environmental dependencies such as a physical database connection to insert, update, delete or retrieve your data. However when performing unit tests it is often much more efficient and productive to remove environmental dependencies. Instead you will need to fake these dependencies. Faking a database (also known as mocking) can be relatively straight forward but the version of Entity Framework released with .Net 3.5 SP1 has a number of implementation specifics which actually makes faking the existence of a database quite difficult. Faking Entity Framework As mentioned earlier, to effectively unit test you will need to fake/simulate Entity Framework calls to the database. There are many free open source mocking frameworks that can help you achieve this but it will require additional effort to overcome & workaround a number of limitations in those frameworks. Examples of these limitations include: Not able to fake calls to non virtual methods Not able to fake sealed classes Not able to fake LINQ to Entities queries (replace database calls with in-memory collection calls) There is a mocking framework which is flexible enough to handle limitations such as those above. The commercially available TypeMock Isolator can do the job for you with less code and ultimately more readable unit tests. I’m going to demonstrate tackling one of those limitations using MoQ as my mocking framework. Then I will tackle the same issue using TypeMock Isolator. Mocking Entity Framework with MoQ One basic need when faking Entity Framework is to fake the ObjectContext. This cannot be done by passing any connection string. You have to pass a correct Entity Framework connection string that specifies CSDL, SSDL and MSL locations along with a provider connection string. Assuming we are going to do that, we’ll explore another limitation. The limitation we are going to face now is related to not being able to fake calls to non-virtual/overridable members with MoQ. I have the following repository method that adds an EntityObject (instance of a Blog entity) to Blogs entity set in an ObjectContext. public override void Add(Blog blog) { if(BlogContext.Blogs.Any(b=>b.Name == blog.Name)) { throw new InvalidOperationException("Blog with same name already exists!"); } BlogContext.AddToBlogs(blog); } The method does a very simple check that the name of the new Blog entity instance doesn’t exist. This is done through the simple LINQ query above. If the blog doesn’t already exist it simply adds it to the current context to be saved when SaveChanges of the ObjectContext instance (e.g. BlogContext) is called. However, if a blog with the same name exits, and exception (InvalideOperationException) will be thrown. Let us now create a unit test for the Add method using MoQ. [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Add_Should_Throw_InvalidOperationException_When_Blog_With_Same_Name_Already_Exits() { //(1) We shouldn't depend on configuration when doing unit tests! But, //its a workaround to fake the ObjectContext string connectionString = ConfigurationManager .ConnectionStrings["MyBlogConnString"] .ConnectionString; //(2) Arrange: Fake ObjectContext var fakeContext = new Mock<MyBlogContext>(connectionString); //(3) Next Line will pass, as ObjectContext now can be faked with proper connection string var repo = new BlogRepository(fakeContext.Object); //(4) Create fake ObjectQuery<Blog>. Will be used to substitute MyBlogContext.Blogs property var fakeObjectQuery = new Mock<ObjectQuery<Blog>>("[Blogs]", fakeContext.Object); //(5) Arrange: Set Expectations //Next line will throw an exception by MoQ: //System.ArgumentException: Invalid setup on a non-overridable member fakeContext.SetupGet(c=>c.Blogs).Returns(fakeObjectQuery.Object); fakeObjectQuery.Setup(q => q.Any(b => b.Name == "NewBlog")).Returns(true); //Act repo.Add(new Blog { Name = "NewBlog" }); } This test method is checking to see if the correct exception ([ExpectedException(typeof(InvalidOperationException))]) is thrown when a developer attempts to Add a blog with a name that’s already exists. On (1) a connection string is initialized from configuration file. To retrieve the full connection string. On (2) a fake ObjectContext is being created. The ObjectContext here is MyBlogContext and its being created using this var fakeContext = new Mock<MyBlogContext>(connectionString); This way a fake context is being created using MoQ. On (3) a BlogRepository instance is created. BlogRepository has dependency on generate Entity Framework ObjectContext, MyObjectContext. And so the fake context is passed to the constructor. var repo = new BlogRepository(fakeContext.Object); On (4) a fake instance of ObjectQuery<Blog> is being created to use as a substitute to MyObjectContext.Blogs property as we will see in (5). On (5) setup an expectation for calling Blogs property of MyBlogContext and substitute the return result with the fake ObjectQuery<Blog> instance created on (4). When you run this test it will fail with MoQ throwing an exception because of this line: fakeContext.SetupGet(c=>c.Blogs).Returns(fakeObjectQuery.Object); This happens because the generate property MyBlogContext.Blogs is not virtual/overridable. And assuming it is virtual or you managed to make it virtual it will fail at the following line throwing the same exception: fakeObjectQuery.Setup(q => q.Any(b => b.Name == "NewBlog")).Returns(true); This time the test will fail because the Any extension method is not virtual/overridable. You won’t be able to replace ObjectQuery<Blog> with fake in memory collection to test your LINQ to Entities queries. Now lets see how replacing MoQ with TypeMock Isolator can help. Mocking Entity Framework with TypeMock Isolator The following is the same test method we had above for MoQ but this time implemented using TypeMock Isolator: [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Add_New_Blog_That_Already_Exists_Should_Throw_InvalidOperationException() { //(1) Create fake in memory collection of blogs var fakeInMemoryBlogs = new List<Blog> {new Blog {Name = "FakeBlog"}}; //(2) create fake context var fakeContext = Isolate.Fake.Instance<MyBlogContext>(); //(3) Setup expected call to MyBlogContext.Blogs property through the fake context Isolate.WhenCalled(() => fakeContext.Blogs) .WillReturnCollectionValuesOf(fakeInMemoryBlogs.AsQueryable()); //(4) Create new blog with a name that already exits in the fake in memory collection in (1) var blog = new Blog {Name = "FakeBlog"}; //(5) Instantiate instance of BlogRepository (Class under test) var repo = new BlogRepository(fakeContext); //(6) Acting by adding the newly created blog () repo.Add(blog); } When running the above test method it will pass as the Add method of BlogRepository is going to throw an InvalidOperationException which is the expected behaviour. Nothing prevents us from faking out the database interaction! Even faking ObjectContext  at (2) didn’t require a connection string. On (3) Isolator sets up a faking result for MyBlogContext.Blogs when its being called through the fake instance fakeContext created on (2). The faking result is just an in-memory collection declared an initialized on (1). Finally at (6) action we call the Add method of BlogRepository passing a new Blog instance that has a name that’s already exists in the fake in-memory collection which we set up at (1). As expected the test will pass because it will throw the expected exception defined on top of the test method - InvalidOperationException. TypeMock Isolator succeeded in faking Entity Framework with ease. Conclusion We explored how to write a simple unit test using TypeMock Isolator for code which is using Entity Framework. We also explored a few of the limitations of other mocking frameworks which TypeMock is successfully able to handle. There are workarounds that you can use to overcome limitations when using MoQ or Rhino Mock, however the workarounds will require you to write more code and your tests will likely be more complex. For a comparison between different mocking frameworks take a look at this document produced by TypeMock. You might also want to check out this open source project to compare mocking frameworks. I hope you enjoyed this post Muhammad Mosa http://mosesofegypt.net/ http://twitter.com/mosessaur Screencast of unit testing Entity Framework Related Links GuestPost: Introduction to Mocking GuesPost: Typemock Isolator – Much more than an Isolation framework

    Read the article

  • Rob Blackwell on interoperability and Azure

    - by Eric Nelson
    At QCon in March we had a sample Azure application implemented in both Java and Ruby to demonstrate that the Windows Azure Platform is not just about .NET. The following is an interesting interview with Rob Blackwell, the R&D director of the partner who implemented the application. UK Interoperability Team Interviews Rob Blackwell, R&D Director at Active Web Solutions. Is Microsoft taking interoperability seriously? Yes. In the past, I think Microsoft has, quite rightly come in for criticism, but architects and developers should look at this again. The Interoperability Bridges site (http://www.interoperabilitybridges.com/ ) shows a wide range of projects that allow interoperability from Java, Ruby and PHP for example. The Windows Azure platform has been architected with interoperable APIs in mind. It's straightforward to access the various storage facilities from just about any language or platform. Azure compute is capable of running more than just C# applications! Why is interoperability important to you? My company provides consultancy and bespoke development services. We're a Microsoft Gold Partner, but we live in the real world where companies have a mix of technologies provided by a variety of vendors. When developing an enterprise software solution, you rarely have a completely blank canvas. We often see integration scenarios where we need to exchange data with legacy systems. It's not unusual to see modern Silverlight applications being built on top of Java or Mainframe based back ends. Could you give us some examples of where interoperability has been important for your projects? We developed an innovative Sea Safety system for the RNLI Lifeboats here in the UK. Commercial Fishing is one of the most dangerous professions and we helped developed the MOB Guardian System which uses satellite technology and man overboard devices to raise the alarm when a fisherman gets into trouble. The solution is implemented in .NET running on Windows, but without interoperable standards, it would have been impossible to communicate with the satellite gateway technology. For more information, please see the case study: http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?CaseStudyID=4000005892 More recently, we were asked to build a web site to accompany the QCon 2010 conference in London to help demonstrate and promote interoperability. We built the site using Java and Restlet and hosted it in Windows Azure Compute. The site accepts feedback from visitors and all the data is stored in Windows Azure Storage. We also ported the application to Ruby on Rails for demonstration purposes. Visitors to the stand were surprised that this was even possible. Why should Java developers be interested in Windows Azure? Windows Azure Storage consists of Blobs, Queues and Tables. The storage is scalable, durable, secure and cost-effective. Using the WindowsAzure4j library, it's easy to use, and takes just a few lines of code. If you are writing an application with large data storage requirements, or you want an offsite backup, it makes a lot of sense. Running Java applications in Azure Compute is straightforward with tools like the Tomcat Solution Accelerator (http://code.msdn.microsoft.com/winazuretomcat )and AzureRunMe (http://azurerunme.codeplex.com/ ). The Windows Azure AppFabric Service Bus can also be used to connect heterogeneous systems running on different networks and in different data centres. How can The Service Bus be considered an interoperability solution? I think that the Windows Azure AppFabric Service Bus is one of Microsoft’s best kept secrets. Think of it as “a globally scalable application plumbing kit in the sky”. If you have used Enterprise Service Buses before, you’ll be familiar with the concept. Applications can connect to the service bus to securely exchange data – these can be point to point or multicast links. With the AppFabric Service Bus, the applications can exist anywhere that has access to the Internet and the connections can traverse firewalls. This makes it easy to extend or scale your application or reach out to other networks and technologies. For example, let’s say you have a SQL Server database running on premises and you want to expose the data to a Java application running in the cloud. You could set up a point to point Service Bus connection and use JDBC. Traditionally this would have been difficult or impossible without punching holes in firewalls and compromising security. Rob Blackwell is R&D Director at Active Web Solutions, www.aws.net , a Microsoft Gold Partner specialising in leading edge software solutions. He is an occasional writer and conference speaker and blogs at www.robblackwell.org.uk Related Links: UK Azure Online Community – join today. UK Windows Azure Site Start working with Windows Azure

    Read the article

  • 5 Steps to getting started with IronRuby

    - by Eric Nelson
    IronRuby is a Open Source implementation of the Ruby programming language for .NET, heavily relying on Microsoft's Dynamic Language Runtime. The project's #1 goal is to be a true Ruby implementation, meaning it runs existing Ruby code. Check out this summary of using the Ruby standard library and 3rd party libraries in IronRuby. IronRuby has tight integration with .NET, so any .NET types can be used from IronRuby and the IronRuby runtime can be embedded into any .NET application. These 5 steps should get you nicely up and running on IronRuby – OR … you could just watch a video session from the lead developer which took place earlier this month (March 2010 - 60mins). But the 5 steps will be quicker :-) Step 1 – Install IronRuby :-) You can install IronRuby automatically using an MSI or manually. For simplicity I would recommend the MSI install. TIP: As of the 25th of March IronRuby has not quite shipped. The download above is a Release Candidate (RC) which means it is still undergoing final testing by the team. You will need to uninstall this version (RC3) once the final release is available. The good news is that uninstalling IronRuby RC3 will work without a hitch as the MSI does relatively little. Step 2 – Install an IronRuby friendly editor You will need to Install an editor to work with IronRuby as there is no designer support for IronRuby inside Visual Studio. There are many editors to choose from but I would recommend you either went with: SciTE (Download the MSI): This is a lightweight text editor which is simple to get up and running. SciTE understands Ruby syntax and allows you to easily run IronRuby code within the editor with a small change to the config file. SharpDevelop 3.2 (Download the MSI): This is an open source development environment for C#, VB, Boo and now IronRuby. IronRuby support is new but it does include integrated debugging. You might also want to check out the main site for SharpDevelop. TIP: There are commercial tools for Ruby development which offer richer support such as intellisense.. They can be coerced into working with IronRuby. A good one to start with is RubyMine which needs some small changes to make it work with IronRuby. Step 3 – Run the IronRuby Tutorial Run through the IronRuby tutorial which is included in the IronRuby download. It covers off the basics of the Ruby languages and how IronRuby integrates with .NET. In a typical install it will end up at C:\Program Files\IronRuby 0.9.4.0\Samples\Tutorial. Which will give you the tutorial implemented in .NET and Ruby. TIP: You might also want to check out these two introductory posts Using IronRuby and .NET to produce the ‘Hello World of WPF’ and What's IronRuby, and how do I put it on Rails? Step 4 – Get some good books to read Get a great book on Ruby and IronRuby. There are several free ebooks on Ruby which will help you learn the language. The little book of Ruby is a good place to start. I would also recommend you purchase IronRuby Unleashed (Buy on Amazon UK | Buy on Amazon USA). You might also want to check out this mini-review. Other books are due out soon including IronRuby in Action. TIP: Also check out the official documentation for using .NET from IronRuby. Step 5 – Keep an eye on the team blogs Keep an eye on the IronRuby team blogs including Jimmy Schementi, Jim Deville and Tomas Matousek (full list) TIP: And keep a watch out for the final release of IronRuby – due anytime soon!

    Read the article

  • What is Python 20th and final guideline

    - by Eric
    Sometimes when my life needs some guiding light, I read the Zen of Python by Tim Peters and usually manage to get back on the tracks. Today was one of those days, so I checked it again. I've noticed that the "abstract" section says: Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down. What would be this last unwritten aphorism?

    Read the article

  • Ubuntu 12.04 installation never finishes

    - by Eric Carlsson
    I am trying to install Ubuntu 12.04 on an old Dell Latitude C400 laptop previously running windows XP using an Ubuntu install CD. The OS runs fine off the CD if a bit slow, and the installation starts off fine. However once the progress bar is filled I get put back to the desktop and nothing happens, first I assumed that the installation was completed but when I restarted the computer and booted from the hard drive nothing happened. I tried to install a few more times but the same thing happens. Am I doing something wrong? I do not get a error message or a installation complete notification. Is there any way I could get some kind of debug screen or log to see if something went wrong or at least follow the installation progress in more detail. Thanks for the help.

    Read the article

  • Stop Believing TV’s Lies: The Real Truth About "Enhancing" Images

    - by Eric Z Goodnight
    You’ve seen it over and over. The FBI uses their advanced technology to “enhance” a blurry image, and find a villain’s face in the worst possible footage. Well, How-To Geek is calling their bluff. Read on to see why. It’s one of the most common tropes in television and movies, but is there any possibility a government agency could really have the technology to find faces where there are only blurry pixels? We’ll make the argument that not only is it impossible with current technology, but it is very unlikely to ever be a technology we’ll ever see. Stick around to see us put this trope under the lenses of science and technology, and prove it wrong once and for all Latest Features How-To Geek ETC Stop Believing TV’s Lies: The Real Truth About "Enhancing" Images The How-To Geek Valentine’s Day Gift Guide Inspire Geek Love with These Hilarious Geek Valentines RGB? CMYK? Alpha? What Are Image Channels and What Do They Mean? How to Recover that Photo, Picture or File You Deleted Accidentally How To Colorize Black and White Vintage Photographs in Photoshop A History of Vintage Transformers: Decepticons Edition [Infographic] How to Determine What Kind of Comment to Leave on Facebook [Humorous Flow Chart] View the Cars of Tomorrow Through the Eyes of the Past [Historical Video] Add Romance to Your Desktop with These Two Valentine’s Day Themes for Windows 7 Gmail’s Priority Inbox Now Available for Mobile Web Browsers Touchpad Blocker Locks Down Your Touchpad While Typing

    Read the article

  • SyncToBlog #12 Windows Azure and Cloud Links

    - by Eric Nelson
    Some more “syncing to paper” :) Steve Marx wrote a very interesting article about using Hosted Web Core in an Azure Worker Role. Hosted Web Core is a new feature in IIS 7 that enables developers to create applications that load the core IIS functionality. Wade Wegner is a new Technical Evangelist for Windows Azure platform AppFabric Example from Wade (and how I found him) Host WCF Services in IIS with Service Bus Endpoints Google and vmware “get engaged” over cloud http://googlecode.blogspot.com/2010/05/enabling-cloud-portability-with-google.html A new cloud comparison site – slick but limited coverage (it is not at Azure level, rather BPOS level) www.cloudhypermarket.com  The Rise of NoSQL Database (devx free registration required) Moe Khosravy talks about Codename "Dallas"  to my colleague David G (14min video) New videos Calculating the cost of Azure and Calculating the cost of SQL Azure Related Links: Previous SyncToBlog posts My delicious bookmarks

    Read the article

  • Macs Don’t Make You Creative! So Why Do Artists Really Love Apple?

    - by Eric Z Goodnight
    Chances are you have at least one “creative” friend who’s a Mac advocate. Ever wondered how Apple got a reputation as the “creative company,” or why artists are so drawn to them? Surely, computers can’t make you creative, can they? Maybe you’re an avid Mac Hater, or maybe you’re an Apple advocate—chances are you’ve heard of this myth and wonder why people all seem to think this way. Take a look through the history of Apple, and see why Macintosh has become so synonymous with desktop publishing, photography, creativity, and design industries. Latest Features How-To Geek ETC Macs Don’t Make You Creative! So Why Do Artists Really Love Apple? MacX DVD Ripper Pro is Free for How-To Geek Readers (Time Limited!) HTG Explains: What’s a Solid State Drive and What Do I Need to Know? How to Get Amazing Color from Photos in Photoshop, GIMP, and Paint.NET Learn To Adjust Contrast Like a Pro in Photoshop, GIMP, and Paint.NET Have You Ever Wondered How Your Operating System Got Its Name? Sync Blocker Stops iTunes from Automatically Syncing The Journey to the Mystical Forest [Wallpaper] Trace Your Browser’s Roots on the Browser Family Tree [Infographic] Save Files Directly from Your Browser to the Cloud in Chrome and Iron The Steve Jobs Chronicles – Charlie and the Apple Factory [Video] Google Chrome Updates; Faster, Cleaner Menus, Encrypted Password Syncing, and More

    Read the article

  • ISO Mount for Windown 7 and/or Server 2008

    - by Eric Johnson
    Apparently it's hard to locate a free ISO mapper these days.  Like most people I've use Microsoft's Virtual CD ROM to mount ISO images on XP and server 2003 machines.   This will not work in Windows 7 and Server 2008 machines.  Therefore, I recommend people try out magic ISO instead.   It's freeware and can be downloaded from the following URL. http://www.magiciso.com/tutorials/miso-magicdisc-history.htm

    Read the article

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