Search Results

Search found 1031 results on 42 pages for 'lightweight'.

Page 11/42 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Should a Perl constructor return an undef or a "invalid" object?

    - by DVK
    Question: What is considered to be "Best practice" - and why - of handling errors in a constructor?. "Best Practice" can be a quote from Schwartz, or 50% of CPAN modules use it, etc...; but I'm happy with well reasoned opinion from anyone even if it explains why the common best practice is not really the best approach. As far as my own view of the topic (informed by software development in Perl for many years), I have seen three main approaches to error handling in a perl module (listed from best to worst in my opinion): Construct an object, set an invalid flag (usually "is_valid" method). Often coupled with setting error message via your class's error handling. Pros: Allows for standard (compared to other method calls) error handling as it allows to use $obj->errors() type calls after a bad constructor just like after any other method call. Allows for additional info to be passed (e.g. 1 error, warnings, etc...) Allows for lightweight "redo"/"fixme" functionality, In other words, if the object that is constructed is very heavy, with many complex attributes that are 100% always OK, and the only reason it is not valid is because someone entered an incorrect date, you can simply do "$obj->setDate()" instead of the overhead of re-executing entire constructor again. This pattern is not always needed, but can be enormously useful in the right design. Cons: None that I'm aware of. Return "undef". Cons: Can not achieve any of the Pros of the first solution (per-object error messages outside of global variables and lightweight "fixme" capability for heavy objects). Die inside the constructor. Outside of some very narrow edge cases, I personally consider this an awful choice for too many reasons to list on the margins of this question. UPDATE: Just to be clear, I consider the (otherwise very worthy and a great design) solution of having very simple constructor that can't fail at all and a heavy initializer method where all the error checking occurs to be merely a subset of either case #1 (if initializer sets error flags) or case #3 (if initializer dies) for the purposes of this question. Obviously, choosing such a design, you automatically reject option #2.

    Read the article

  • Programmatical Creation of NSMappingModel

    - by enchilada
    I want to programmatically (without Lightweight Migration) create a mapping model between two models that are exactly the same, except one of the entities (there are a bunch of entities) has different attributes. Let's call this entity "Person". And let's say the destination model has 1) added a new attribute called "address" 2) deleted an attribute called "eyeColor" 3) kept (i.e. not done anything with) an attribute called "name" How would you create an NSMappingModel between these models programmatically? I happen to have some explicit questions that might help me do this by myself: Q1) Do I have to create NSEntityMapping objects for all of the entities other than "Person", even if they remain unchanged? Q2) How do I deal with the "address" attribute in "Person", which is a new one being created? Should I create an NSPropertyMapping for that somehow, that turns nothing into something ("address")? Q3) How do I deal with the "name" attribute in "Person"? Do I have to create an NSPropertyMapping for that, even though it simply stays the same? Q4) For the NSEntityMapping corresponding to "Person", is not creating any NSPropertyMapping for "eyeColor" a proper way to get it deleted? Or should I create an NSPropertyMapping for "eyeColor"? If yes, how would this object be created, i.e. what would determine that its purpose is to get rid of "eyeColor"? Thank you in advance, and I apologize not being able to answer these questions myself, as the documenation really has no good example of how to create NSMappingModels programmatically. Note again that I'm not allowed to use Lightweight Migration. I must do this manually.

    Read the article

  • Which Javascript framework (jQuery vs Dojo vs ... )?

    - by cletus
    There are a few Javascript frameworks/toolets out there, such as: jQuery; Dojo; Prototype; YUI; MooTools; ExtJS; SmartClient; and others I'm sure. It certainly seems that jQuery is ascendant in terms of mindshare at the moment. For example, Microsoft (ASP.NET MVC) and Nokia will use it. I also found this this performance comparison of Dojo, jQuery, MooTools and Prototype (Edit: Updated Comparison), which looks highly favourable to Dojo and jQuery. Now my previous experience with Javascript has been the old school HTML + Javascript most of us have done and RIA frameworks like Google Web Toolkit ("GWT") and Ext-GWT, which were a fairly low-stress entry into the Ajax world for someone from a Java background, such as myself. But, after all this, I find myself leaning towards the more PHP + Ajax type solution, which just seems that much more lightweight. So I've been looking into jQuery and I really like it's use of commands, the use of fluent interfaces and method chaining, it's cross-browser CSS selector superset, the fact that it's lightweight and extensible, the brevity of the syntax, unobtrusive Javascript and the plug-in framework. Now obviously many of these aren't unique to jQuery but on the basis that some things are greater than their sum of parts, it just seems that it all fits together and works well. So jQuery seems to have a lot going for it and it looks to the frontrunner for what I choose to concentrate on. Is there anything else I should be aware of or any particular reasons not to choose it or to choose something else? EDIT: Just wanted to add this trend comparison of Javascript frameworks.

    Read the article

  • AJAX Autosave

    - by antony.trupe
    What's the best javascript library, or plugin or extension to a library, that has implemented autosaving functionality? The specific need is to be able to 'save' a data grid. Think gmail and Google Documents' autosave. I don't want to reinvent the wheel if its already been invented. I'm looking for an existing implementation of the magical autoSave() function. Auto-Saving:pushing to server code that saves to persistent storage, usually a DB. The server code framework is outside the scope of this question. Note that I'm not looking for an Ajax library, but a library/framework a level higher: interacts with the form itself. daemach introduced an implementation on top of jQuery @ http://ideamill.synaptrixgroup.com/?p=3. I'm not convinced it meets the lightweight and well engineered criteria though. Criteria stable, lightweight, well engineered saves onChange and/or onBlur saves no more frequently then a given number of milliseconds handles multiple updates happening at the same time doesn't save if no change has occurred since last save saves to different urls per input class Updates I've stabilized a solution. See my answer below for links.

    Read the article

  • Semantically linking to code snippets

    - by Tim
    What's the most simple and semantic way of presenting code snippets in HTML? Possible XHTML syntax <a href="code_sample.php" type="text/x-php"> Example of widget creation </a> Example of linked file (code_sample.php): // Create a new widget $widget = new widget(); Pros: Semantically uses title to describe the source code being referenced Up to the client to render snippet Having very many custom server-side implementations tells me it should be standardized Browsers can have plug-ins for copy+paste, download, etc Seems to me this is where it belongs (not in Javascript) Degradation: non-compliant browsers receive a link to the associated content Cons: Not semantic enough? Seems wrong to replace hyperlinks with source code for presentation <object> might be better, but wouldn't degrade as nicely. Background I'm trying to create a "personal" XHTML standard for storing notes (wow, this is probably among the nerdiest things I've said). Since notes are just "scratch" it needs to be very lightweight. SO's markdown is very lightweight but not semantic enough for my needs. Plus, now I'm just curious. What's the most ideal syntax for linking to client-rendered code-snippets?

    Read the article

  • Updating section in ConfigParser (or an alternative)

    - by lyrae
    I am making a plugin for another program and so I am trying to make thing as lightweight as possible. What i need to do is be able to update the name of a section in the ConfigParser's config file. [project name] author:john doe email: [email protected] year: 2010 I then have text fields where user can edit project's name, author, email and year. I don't think changing [project name] is possible, so I have thought of two solutions: 1 -Have my config file like this: [0] projectname: foobar author:john doe email: [email protected] year: 2010 that way i can change project's name just like another option. But the problem is, i would need the section # to be auto incremented. And to do this i would have to get every section, sort of, and figure out what the next number should be. The other option would be to delete the entire section and its value, and re-add it with the updated values which would require a little more work as well, such as passing a variable that holds the old section name through functions, etc, but i wouldn't mind if it's faster. Which of the two is best? or is there another way? I am willing to go with the fastest/lightweight solution possible, doesn't matter if it requires more work or not.

    Read the article

  • C++ IDE for Linux?

    - by Sven
    I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: Lightweight IDE for linux and What tools do you use to develop C++ applications on Linux? I'm not looking for a lightweight IDE. If an IDE is worth the money, then I will pay for it, so it need not be free. My question, then: What good, C++ programming IDE is available for Linux? The minimums are fairly standard: syntax highlighting, code completion (like intellisense or its Eclipse counterpart) and integrated debugging (e.g., basic breakpoints). I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that Eclipse supports C++, and I really like that IDE for Java, but is it any good for C++ and is there something better? The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages? Maybe my question should therefore be: What IDE do you propose (given your experiences), and why?

    Read the article

  • Generating HTML Programmatically in C#, Targeting Printed Reports

    - by John Passaniti
    I've taken over a C# (2.0) code base that has the ability to print information. The code to do this is insanely tedious. Elements are drawn onto each page, with magic constants representing positioning. I imagine the programmer sitting with a ruler, designing each page by measuring and typing in the positions. And yes, one could certainly come up with some nice abstractions to make this approach rational. But I am looking at a different method. The idea is that I'll replace the current code that prints with code that generates static HTML pages, saves them to a file, and then launches the web browser on that file. The most obvious benefit is that I don't have to deal with formatting-- I can let the web browser do that for me with tags and CSS. So what I am looking for is a very lightweight set of classes that I can use to help generate HTML. I don't need anything as heavyweight as HTMLTextWriter. What I'm looking for is something to avoid fragments like this: String.Format("<tr><td>{0}</td><td>{1}</td></tr>", foo, bar); And instead take have this kind of feel: ... table(). tr(). td(foo). td(bar) Or something like that. I've seen lightweight classes like that for other languages but can't find the equivalent (or better) for C#. I can certainly write it myself, but I'm a firm believer in not reinventing wheels. Know anything like this? Know anything better than this?

    Read the article

  • Generating EF Code First model classes from an existing database

    - by Jon Galloway
    Entity Framework Code First is a lightweight way to "turn on" data access for a simple CLR class. As the name implies, the intended use is that you're writing the code first and thinking about the database later. However, I really like the Entity Framework Code First works, and I want to use it in existing projects and projects with pre-existing databases. For example, MVC Music Store comes with a SQL Express database that's pre-loaded with a catalog of music (including genres, artists, and songs), and while it may eventually make sense to load that seed data from a different source, for the MVC 3 release we wanted to keep using the existing database. While I'm not getting the full benefit of Code First - writing code which drives the database schema - I can still benefit from the simplicity of the lightweight code approach. Scott Guthrie blogged about how to use entity framework with an existing database, looking at how you can override the Entity Framework Code First conventions so that it can work with a database which was created following other conventions. That gives you the information you need to create the model classes manually. However, it turns out that with Entity Framework 4 CTP 5, there's a way to generate the model classes from the database schema. Once the grunt work is done, of course, you can go in and modify the model classes as you'd like, but you can save the time and frustration of figuring out things like mapping SQL database types to .NET types. Note that this template requires Entity Framework 4 CTP 5 or later. You can install EF 4 CTP 5 here. Step One: Generate an EF Model from your existing database The code generation system in Entity Framework works from a model. You can add a model to your existing project and delete it when you're done, but I think it's simpler to just spin up a separate project to generate the model classes. When you're done, you can delete the project without affecting your application, or you may choose to keep it around in case you have other database schema updates which require model changes. I chose to add the Model classes to the Models folder of a new MVC 3 application. Right-click the folder and select "Add / New Item..."   Next, select ADO.NET Entity Data Model from the Data Templates list, and name it whatever you want (the name is unimportant).   Next, select "Generate from database." This is important - it's what kicks off the next few steps, which read your database's schema.   Now it's time to point the Entity Data Model Wizard at your existing database. I'll assume you know how to find your database - if not, I covered that a bit in the MVC Music Store tutorial section on Models and Data. Select your database, uncheck the "Save entity connection settings in Web.config" (since we won't be using them within the application), and click Next.   Now you can select the database objects you'd like modeled. I just selected all tables and clicked Finish.   And there's your model. If you want, you can make additional changes here before going on to generate the code.   Step Two: Add the DbContext Generator Like most code generation systems in Visual Studio lately, Entity Framework uses T4 templates which allow for some control over how the code is generated. K Scott Allen wrote a detailed article on T4 Templates and the Entity Framework on MSDN recently, if you'd like to know more. Fortunately for us, there's already a template that does just what we need without any customization. Right-click a blank space in the Entity Framework model surface and select "Add Code Generation Item..." Select the Code groupt in the Installed Templates section and pick the ADO.NET DbContext Generator. If you don't see this listed, make sure you've got EF 4 CTP 5 installed and that you're looking at the Code templates group. Note that the DbContext Generator template is similar to the EF POCO template which came out last year, but with "fix up" code (unnecessary in EF Code First) removed.   As soon as you do this, you'll two terrifying Security Warnings - unless you click the "Do not show this message again" checkbox the first time. It will also be displayed (twice) every time you rebuild the project, so I checked the box and no immediate harm befell my computer (fingers crossed!).   Here's the payoff: two templates (filenames ending with .tt) have been added to the project, and they've generated the code I needed.   The "MusicStoreEntities.Context.tt" template built a DbContext class which holds the entity collections, and the "MusicStoreEntities.tt" template build a separate class for each table I selected earlier. We'll customize them in the next step. I recommend copying all the generated .cs files into your application at this point, since accidentally rebuilding the generation project will overwrite your changes if you leave them there. Step Three: Modify and use your POCO entity classes Note: I made a bunch of tweaks to my POCO classes after they were generated. You don't have to do any of this, but I think it's important that you can - they're your classes, and EF Code First respects that. Modify them as you need for your application, or don't. The Context class derives from DbContext, which is what turns on the EF Code First features. It holds a DbSet for each entity. Think of DbSet as a simple List, but with Entity Framework features turned on.   //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EF_CodeFirst_From_Existing_Database.Models { using System; using System.Data.Entity; public partial class Entities : DbContext { public Entities() : base("name=Entities") { } public DbSet<Album> Albums { get; set; } public DbSet<Artist> Artists { get; set; } public DbSet<Cart> Carts { get; set; } public DbSet<Genre> Genres { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } public DbSet<Order> Orders { get; set; } } } It's a pretty lightweight class as generated, so I just took out the comments, set the namespace, removed the constructor, and formatted it a bit. Done. If I wanted, though, I could have added or removed DbSets, overridden conventions, etc. using System.Data.Entity; namespace MvcMusicStore.Models { public class MusicStoreEntities : DbContext { public DbSet Albums { get; set; } public DbSet Genres { get; set; } public DbSet Artists { get; set; } public DbSet Carts { get; set; } public DbSet Orders { get; set; } public DbSet OrderDetails { get; set; } } } Next, it's time to look at the individual classes. Some of mine were pretty simple - for the Cart class, I just need to remove the header and clean up the namespace. //------------------------------------------------------------------------------ // // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace EF_CodeFirst_From_Existing_Database.Models { using System; using System.Collections.Generic; public partial class Cart { // Primitive properties public int RecordId { get; set; } public string CartId { get; set; } public int AlbumId { get; set; } public int Count { get; set; } public System.DateTime DateCreated { get; set; } // Navigation properties public virtual Album Album { get; set; } } } I did a bit more customization on the Album class. Here's what was generated: //------------------------------------------------------------------------------ // // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace EF_CodeFirst_From_Existing_Database.Models { using System; using System.Collections.Generic; public partial class Album { public Album() { this.Carts = new HashSet(); this.OrderDetails = new HashSet(); } // Primitive properties public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } // Navigation properties public virtual Artist Artist { get; set; } public virtual Genre Genre { get; set; } public virtual ICollection Carts { get; set; } public virtual ICollection OrderDetails { get; set; } } } I removed the header, changed the namespace, and removed some of the navigation properties. One nice thing about EF Code First is that you don't have to have a property for each database column or foreign key. In the Music Store sample, for instance, we build the app up using code first and start with just a few columns, adding in fields and navigation properties as the application needs them. EF Code First handles the columsn we've told it about and doesn't complain about the others. Here's the basic class: using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using System.Collections.Generic; namespace MvcMusicStore.Models { public class Album { public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public virtual List OrderDetails { get; set; } } } It's my class, not Entity Framework's, so I'm free to do what I want with it. I added a bunch of MVC 3 annotations for scaffolding and validation support, as shown below: using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using System.Collections.Generic; namespace MvcMusicStore.Models { [Bind(Exclude = "AlbumId")] public class Album { [ScaffoldColumn(false)] public int AlbumId { get; set; } [DisplayName("Genre")] public int GenreId { get; set; } [DisplayName("Artist")] public int ArtistId { get; set; } [Required(ErrorMessage = "An Album Title is required")] [StringLength(160)] public string Title { get; set; } [Required(ErrorMessage = "Price is required")] [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")] public decimal Price { get; set; } [DisplayName("Album Art URL")] [StringLength(1024)] public string AlbumArtUrl { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public virtual List<OrderDetail> OrderDetails { get; set; } } } The end result was that I had working EF Code First model code for the finished application. You can follow along through the tutorial to see how I built up to the finished model classes, starting with simple 2-3 property classes and building up to the full working schema. Thanks to Diego Vega (on the Entity Framework team) for pointing me to the DbContext template.

    Read the article

  • C#/.NET Little Wonders: ConcurrentBag and BlockingCollection

    - by James Michael Hare
    In the first week of concurrent collections, began with a general introduction and discussed the ConcurrentStack<T> and ConcurrentQueue<T>.  The last post discussed the ConcurrentDictionary<T> .  Finally this week, we shall close with a discussion of the ConcurrentBag<T> and BlockingCollection<T>. For more of the "Little Wonders" posts, see C#/.NET Little Wonders: A Redux. Recap As you'll recall from the previous posts, the original collections were object-based containers that accomplished synchronization through a Synchronized member.  With the advent of .NET 2.0, the original collections were succeeded by the generic collections which are fully type-safe, but eschew automatic synchronization.  With .NET 4.0, a new breed of collections was born in the System.Collections.Concurrent namespace.  Of these, the final concurrent collection we will examine is the ConcurrentBag and a very useful wrapper class called the BlockingCollection. For some excellent information on the performance of the concurrent collections and how they perform compared to a traditional brute-force locking strategy, see this informative whitepaper by the Microsoft Parallel Computing Platform team here. ConcurrentBag<T> – Thread-safe unordered collection. Unlike the other concurrent collections, the ConcurrentBag<T> has no non-concurrent counterpart in the .NET collections libraries.  Items can be added and removed from a bag just like any other collection, but unlike the other collections, the items are not maintained in any order.  This makes the bag handy for those cases when all you care about is that the data be consumed eventually, without regard for order of consumption or even fairness – that is, it’s possible new items could be consumed before older items given the right circumstances for a period of time. So why would you ever want a container that can be unfair?  Well, to look at it another way, you can use a ConcurrentQueue and get the fairness, but it comes at a cost in that the ordering rules and synchronization required to maintain that ordering can affect scalability a bit.  Thus sometimes the bag is great when you want the fastest way to get the next item to process, and don’t care what item it is or how long its been waiting. The way that the ConcurrentBag works is to take advantage of the new ThreadLocal<T> type (new in System.Threading for .NET 4.0) so that each thread using the bag has a list local to just that thread.  This means that adding or removing to a thread-local list requires very low synchronization.  The problem comes in where a thread goes to consume an item but it’s local list is empty.  In this case the bag performs “work-stealing” where it will rob an item from another thread that has items in its list.  This requires a higher level of synchronization which adds a bit of overhead to the take operation. So, as you can imagine, this makes the ConcurrentBag good for situations where each thread both produces and consumes items from the bag, but it would be less-than-idea in situations where some threads are dedicated producers and the other threads are dedicated consumers because the work-stealing synchronization would outweigh the thread-local optimization for a thread taking its own items. Like the other concurrent collections, there are some curiosities to keep in mind: IsEmpty(), Count, ToArray(), and GetEnumerator() lock collection Each of these needs to take a snapshot of whole bag to determine if empty, thus they tend to be more expensive and cause Add() and Take() operations to block. ToArray() and GetEnumerator() are static snapshots Because it is based on a snapshot, will not show subsequent updates after snapshot. Add() is lightweight Since adding to the thread-local list, there is very little overhead on Add. TryTake() is lightweight if items in thread-local list As long as items are in the thread-local list, TryTake() is very lightweight, much more so than ConcurrentStack() and ConcurrentQueue(), however if the local thread list is empty, it must steal work from another thread, which is more expensive. Remember, a bag is not ideal for all situations, it is mainly ideal for situations where a process consumes an item and either decomposes it into more items to be processed, or handles the item partially and places it back to be processed again until some point when it will complete.  The main point is that the bag works best when each thread both takes and adds items. For example, we could create a totally contrived example where perhaps we want to see the largest power of a number before it crosses a certain threshold.  Yes, obviously we could easily do this with a log function, but bare with me while I use this contrived example for simplicity. So let’s say we have a work function that will take a Tuple out of a bag, this Tuple will contain two ints.  The first int is the original number, and the second int is the last multiple of that number.  So we could load our bag with the initial values (let’s say we want to know the last multiple of each of 2, 3, 5, and 7 under 100. 1: var bag = new ConcurrentBag<Tuple<int, int>> 2: { 3: Tuple.Create(2, 1), 4: Tuple.Create(3, 1), 5: Tuple.Create(5, 1), 6: Tuple.Create(7, 1) 7: }; Then we can create a method that given the bag, will take out an item, apply the multiplier again, 1: public static void FindHighestPowerUnder(ConcurrentBag<Tuple<int,int>> bag, int threshold) 2: { 3: Tuple<int,int> pair; 4:  5: // while there are items to take, this will prefer local first, then steal if no local 6: while (bag.TryTake(out pair)) 7: { 8: // look at next power 9: var result = Math.Pow(pair.Item1, pair.Item2 + 1); 10:  11: if (result < threshold) 12: { 13: // if smaller than threshold bump power by 1 14: bag.Add(Tuple.Create(pair.Item1, pair.Item2 + 1)); 15: } 16: else 17: { 18: // otherwise, we're done 19: Console.WriteLine("Highest power of {0} under {3} is {0}^{1} = {2}.", 20: pair.Item1, pair.Item2, Math.Pow(pair.Item1, pair.Item2), threshold); 21: } 22: } 23: } Now that we have this, we can load up this method as an Action into our Tasks and run it: 1: // create array of tasks, start all, wait for all 2: var tasks = new[] 3: { 4: new Task(() => FindHighestPowerUnder(bag, 100)), 5: new Task(() => FindHighestPowerUnder(bag, 100)), 6: }; 7:  8: Array.ForEach(tasks, t => t.Start()); 9:  10: Task.WaitAll(tasks); Totally contrived, I know, but keep in mind the main point!  When you have a thread or task that operates on an item, and then puts it back for further consumption – or decomposes an item into further sub-items to be processed – you should consider a ConcurrentBag as the thread-local lists will allow for quick processing.  However, if you need ordering or if your processes are dedicated producers or consumers, this collection is not ideal.  As with anything, you should performance test as your mileage will vary depending on your situation! BlockingCollection<T> – A producers & consumers pattern collection The BlockingCollection<T> can be treated like a collection in its own right, but in reality it adds a producers and consumers paradigm to any collection that implements the interface IProducerConsumerCollection<T>.  If you don’t specify one at the time of construction, it will use a ConcurrentQueue<T> as its underlying store. If you don’t want to use the ConcurrentQueue, the ConcurrentStack and ConcurrentBag also implement the interface (though ConcurrentDictionary does not).  In addition, you are of course free to create your own implementation of the interface. So, for those who don’t remember the producers and consumers classical computer-science problem, the gist of it is that you have one (or more) processes that are creating items (producers) and one (or more) processes that are consuming these items (consumers).  Now, the crux of the problem is that there is a bin (queue) where the produced items are placed, and typically that bin has a limited size.  Thus if a producer creates an item, but there is no space to store it, it must wait until an item is consumed.  Also if a consumer goes to consume an item and none exists, it must wait until an item is produced. The BlockingCollection makes it trivial to implement any standard producers/consumers process set by providing that “bin” where the items can be produced into and consumed from with the appropriate blocking operations.  In addition, you can specify whether the bin should have a limited size or can be (theoretically) unbounded, and you can specify timeouts on the blocking operations. As far as your choice of “bin”, for the most part the ConcurrentQueue is the right choice because it is fairly light and maximizes fairness by ordering items so that they are consumed in the same order they are produced.  You can use the concurrent bag or stack, of course, but your ordering would be random-ish in the case of the former and LIFO in the case of the latter. So let’s look at some of the methods of note in BlockingCollection: BoundedCapacity returns capacity of the “bin” If the bin is unbounded, the capacity is int.MaxValue. Count returns an internally-kept count of items This makes it O(1), but if you modify underlying collection directly (not recommended) it is unreliable. CompleteAdding() is used to cut off further adds. This sets IsAddingCompleted and begins to wind down consumers once empty. IsAddingCompleted is true when producers are “done”. Once you are done producing, should complete the add process to alert consumers. IsCompleted is true when producers are “done” and “bin” is empty. Once you mark the producers done, and all items removed, this will be true. Add() is a blocking add to collection. If bin is full, will wait till space frees up Take() is a blocking remove from collection. If bin is empty, will wait until item is produced or adding is completed. GetConsumingEnumerable() is used to iterate and consume items. Unlike the standard enumerator, this one consumes the items instead of iteration. TryAdd() attempts add but does not block completely If adding would block, returns false instead, can specify TimeSpan to wait before stopping. TryTake() attempts to take but does not block completely Like TryAdd(), if taking would block, returns false instead, can specify TimeSpan to wait. Note the use of CompleteAdding() to signal the BlockingCollection that nothing else should be added.  This means that any attempts to TryAdd() or Add() after marked completed will throw an InvalidOperationException.  In addition, once adding is complete you can still continue to TryTake() and Take() until the bin is empty, and then Take() will throw the InvalidOperationException and TryTake() will return false. So let’s create a simple program to try this out.  Let’s say that you have one process that will be producing items, but a slower consumer process that handles them.  This gives us a chance to peek inside what happens when the bin is bounded (by default, the bin is NOT bounded). 1: var bin = new BlockingCollection<int>(5); Now, we create a method to produce items: 1: public static void ProduceItems(BlockingCollection<int> bin, int numToProduce) 2: { 3: for (int i = 0; i < numToProduce; i++) 4: { 5: // try for 10 ms to add an item 6: while (!bin.TryAdd(i, TimeSpan.FromMilliseconds(10))) 7: { 8: Console.WriteLine("Bin is full, retrying..."); 9: } 10: } 11:  12: // once done producing, call CompleteAdding() 13: Console.WriteLine("Adding is completed."); 14: bin.CompleteAdding(); 15: } And one to consume them: 1: public static void ConsumeItems(BlockingCollection<int> bin) 2: { 3: // This will only be true if CompleteAdding() was called AND the bin is empty. 4: while (!bin.IsCompleted) 5: { 6: int item; 7:  8: if (!bin.TryTake(out item, TimeSpan.FromMilliseconds(10))) 9: { 10: Console.WriteLine("Bin is empty, retrying..."); 11: } 12: else 13: { 14: Console.WriteLine("Consuming item {0}.", item); 15: Thread.Sleep(TimeSpan.FromMilliseconds(20)); 16: } 17: } 18: } Then we can fire them off: 1: // create one producer and two consumers 2: var tasks = new[] 3: { 4: new Task(() => ProduceItems(bin, 20)), 5: new Task(() => ConsumeItems(bin)), 6: new Task(() => ConsumeItems(bin)), 7: }; 8:  9: Array.ForEach(tasks, t => t.Start()); 10:  11: Task.WaitAll(tasks); Notice that the producer is faster than the consumer, thus it should be hitting a full bin often and displaying the message after it times out on TryAdd(). 1: Consuming item 0. 2: Consuming item 1. 3: Bin is full, retrying... 4: Bin is full, retrying... 5: Consuming item 3. 6: Consuming item 2. 7: Bin is full, retrying... 8: Consuming item 4. 9: Consuming item 5. 10: Bin is full, retrying... 11: Consuming item 6. 12: Consuming item 7. 13: Bin is full, retrying... 14: Consuming item 8. 15: Consuming item 9. 16: Bin is full, retrying... 17: Consuming item 10. 18: Consuming item 11. 19: Bin is full, retrying... 20: Consuming item 12. 21: Consuming item 13. 22: Bin is full, retrying... 23: Bin is full, retrying... 24: Consuming item 14. 25: Adding is completed. 26: Consuming item 15. 27: Consuming item 16. 28: Consuming item 17. 29: Consuming item 19. 30: Consuming item 18. Also notice that once CompleteAdding() is called and the bin is empty, the IsCompleted property returns true, and the consumers will exit. Summary The ConcurrentBag is an interesting collection that can be used to optimize concurrency scenarios where tasks or threads both produce and consume items.  In this way, it will choose to consume its own work if available, and then steal if not.  However, in situations where you want fair consumption or ordering, or in situations where the producers and consumers are distinct processes, the bag is not optimal. The BlockingCollection is a great wrapper around all of the concurrent queue, stack, and bag that allows you to add producer and consumer semantics easily including waiting when the bin is full or empty. That’s the end of my dive into the concurrent collections.  I’d also strongly recommend, once again, you read this excellent Microsoft white paper that goes into much greater detail on the efficiencies you can gain using these collections judiciously (here). Tweet Technorati Tags: C#,.NET,Concurrent Collections,Little Wonders

    Read the article

  • CodePlex Daily Summary for Friday, November 25, 2011

    CodePlex Daily Summary for Friday, November 25, 2011Popular ReleasesMiniTwitter: 1.76: MiniTwitter 1.76 ???? ?? ?????????? User Streams ???????????? User Streams ???????????、??????????????? REST ?????????? ?????????????????????????????? ??????????????????????????????Media Companion: MC 3.424b Weekly: Ensure .NET 4.0 Full Framework is installed. (Available from http://www.microsoft.com/download/en/details.aspx?id=17718) Ensure the NFO ID fix is applied when transitioning from versions prior to 3.416b. (Details here) Movie Show Resolutions... Resolved issue when reverting multiselection of movies to "-none-" Added movie rename support for subtitle files '.srt' & '.sub' Finalised code for '-1' fix - radiobutton to choose either filename or title Fixed issue with Movie Batch Wizard Fanart - ...Moskva.FM: V1.5: ????????? ????? ????????? PITER.FM ?????????? ?????? ?????????????? ???????? ???? ????? ???????? ? ????????? ????. ???? ????????? ??????? ????????? ? ????? Lists. ??? ????????? ??????? ??? MOSKVA.FM - ??????? ? ????? Lists txt ???? ?????????? ? ???????? msk ??? ????????? ??????? ??? PITER.FM - ??????? ? ????? Lists txt ???? ?????????? ? ???????? spb ????? ??????? ????????? ?????? ??? ?????? ??????, ????????, ??? ?????????? ??????? ? ?????.ANX.Framework: ANX.Framework Win32 Release v0.4.27: First public alpha release of the ANX.Framework. It is recommended to use the MSI installer package because of security considerations (see documentation Troubleshooting section) of the zip package.Advanced Windows Phone Enginering Tool: WPE Downloads: This version of WPE gives you basic updating, restoring, and, erasing for your Windows Phone device.ASP.NET Comet Ajax Library (Reverse Ajax - Server Push): ASP.NET Reverse Ajax Samples: Chat, MVC Razor, DesktopClient, Reverse Ajax for VB.NET and C#Windows Azure SDK for PHP: Windows Azure SDK for PHP v4.0.5: INSTALLATION Windows Azure SDK for PHP requires no special installation steps. Simply download the SDK, extract it to the folder you would like to keep it in, and add the library directory to your PHP include_path. INSTALLATION VIA PEAR Maarten Balliauw provides an unofficial PEAR channel via http://www.pearplex.net. Here's how to use it: New installation: pear channel-discover pear.pearplex.net pear install pearplex/PHPAzure Or if you've already installed PHPAzure before: pear upgrade p...Anno 2070 Assistant: Beta v1.0 (STABLE): Anno 2070 Assistant Beta v1.0 Released! Features Included: Complete Building Layouts for Ecos, Tycoons & Techs Complete Production Chains for Ecos, Tycoons & Techs Completed Credits Screen Known Issues: Not all production chains and building layouts may be on the lists because they have not yet been discovered. However, data is still 99.9% complete. Currently the Supply & Demand, including Calculator screen are disabled until version 1.1.Minemapper: Minemapper v0.1.7: Including updated Minecraft Biome Extractor and mcmap to support the new Minecraft 1.0.0 release (new block types, etc).Metro Pandora: Metro Pandora SDK V1: Metro Pandora aims to ship a Pandora SDK and apps for XAML .net platforms. For more information on this release please see Metro Pandora SDK Introduction. Supported platforms in V1: Windows Phone 7 / Silverlight Windows 8 .Net 4.0, WPF, WinformsVisual Leak Detector for Visual C++ 2008/2010: v2.2.1: Enhancements: * strdup and _wcsdup functions support added. * Preliminary support for VS 11 added. Bugs Fixed: * Low performance after upgrading from VLD v2.1. * Memory leaks with static linking fixed (disabled calloc support). * Runtime error R6002 fixed because of wrong memory dump format. * version.h fixed in installer. * Some PVS studio warning fixed.NetSqlAzMan - .NET SQL Authorization Manager: 3.6.0.10: 3.6.0.10 22-Nov-2011 Update: Removed PreEmptive Platform integration (PreEmptive analytics) Removed all PreEmptive attributes Removed PreEmptive.dll assembly references from all projects Added first support to ADAM/AD LDS Thanks to PatBea. Work Item 9775: http://netsqlazman.codeplex.com/workitem/9775VideoLan DotNet for WinForm, WPF & Silverlight 5: VideoLan DotNet for WinForm, WPF, SL5 - 2011.11.22: The new version contains Silverlight 5 library: Vlc.DotNet.Silverlight. A sample could be tested here The new version add and correct many features : Correction : Reinitialize some variables Deprecate : Logging API, since VLC 1.2 (08/20/2011) Add subitem in LocationMedia (for Youtube videos, ...) Update Wpf sample to use Youtube videos Many others correctionsSharePoint 2010 FBA Pack: SharePoint 2010 FBA Pack 1.2.0: Web parts are now fully customizable via html templates (Issue #323) FBA Pack is now completely localizable using resource files. Thank you David Chen for submitting the code as well as Chinese translations of the FBA Pack! The membership request web part now gives the option of having the user enter the password and removing the captcha (Issue # 447) The FBA Pack will now work in a zone that does not have FBA enabled (Another zone must have FBA enabled, and the zone must contain the me...SharePoint 2010 Education Demo Project: Release SharePoint SP1 for Education Solutions: This release includes updates to the Content Packs for SharePoint SP1. All Content Packs have been updated to install successfully under SharePoint SP1SQL Monitor - managing sql server performance: SQLMon 4.1 alpha 6: 1. improved support for schema 2. added find reference when right click on object list 3. added object rename supportBugNET Issue Tracker: BugNET 0.9.126: First stable release of version 0.9. Upgrades from 0.8 are fully supported and upgrades to future releases will also be supported. This release is now compiled against the .NET 4.0 framework and is a requirement. Because of this the web.config has significantly changed. After upgrading, you will need to configure the authentication settings for user registration and anonymous access again. Please see our installation / upgrade instructions for more details: http://wiki.bugnetproject.c...Free SharePoint 2010 Sites Templates: SharePoint Server 2010 Sites Templates: here is the list of sites templates to be downloadednopCommerce. Open source shopping cart (ASP.NET MVC): nopcommerce 2.30: Highlight features & improvements: • Performance optimization. • Back in stock notifications. • Product special price support. • Catalog mode (based on customer role) To see the full list of fixes and changes please visit the release notes page (http://www.nopCommerce.com/releasenotes.aspx).Json.NET: Json.NET 4.0 Release 4: Change - JsonTextReader.Culture is now CultureInfo.InvariantCulture by default Change - KeyValurPairConverter no longer cares about the order of the key and value properties Change - Time zone conversions now use new TimeZoneInfo instead of TimeZone Fix - Fixed boolean values sometimes being capitalized when converting to XML Fix - Fixed error when deserializing ConcurrentDictionary Fix - Fixed serializing some Uris returning the incorrect value Fix - Fixed occasional error when...New Projects108Ways: my test siteAdvanced Windows Phone Enginering Tool: Advanced Windows Phone Engineering Tool makes updating, restoring, erasing Windows Phone device easier for end-users and engineers You'll no longer type in command prompt, just browse your update cabinet, and, voila.... It's developed in C# .NET 4.0agileTool: just an ordinary college project but good for learning CRUD in C# and some stuff in wpfArgument Handler: This project aims to help the handling of arguments in command line programs.Atha: Acceptance Testing Heuristics Automation: ATTN: due to codeplex issues w/ source code pushes, I am unable to fully publish the v0.5 release. The source code is provided, but is missing all the references to NuGet packages and other 3rd parties ("/lib"). Currently: Atha allows the user to write automated tests in the scripting languages IronPython, IronRuby, PowerShell, and Razor and to run those tests via a Console program (called "AthaX") or a WPF Windows application (called "Athalon"). Future releases will support a web-supporte...Cerulean: Cerulean provides WP7 a lightweight filesystem in the cloud, hosted on Windows Live SkyDrive and accessible both from the phone and from the desktop. At the time of release, this is the only possible way to share files between your computer and your Windows Phone.CS New: We like CS 1.6!!!Delete Bin, Obj, Backup directories: This utility deletes bin and obj directories recursively (under a specified root directory). It can also delete psess files and files larger than a specific file size. Single-pass, auto-delete multiple bin, obj, and backup directories. DN Projects: Central repository for small learning purposes .net projectsFuya Fuya: ...GeneGuard .NET: Geneguard . NET protect from and inform about SQL & XSS - Injection in ASP .NET WebForms Application. It's developed in C#Havalite CMS: Havalite, a lightweight, open source CMS Blog based on php and SQLite db. It's licensed under the GNU General Public License.Hidetilla: hidetillaIguana: Iguana provides a central language and compiler for creating visually appealing websites that target all major browser platforms quickly. Developers no longer have to create separate versions of web applications for each browser. Iguana is developed in C#.JQuery Ajax Weblinks Donetnuke Module: This is a sample dotnetnuke module which demonstrates a method for adding ajax functionality.JsAction: JsAction is a simple and lightweight RouteHandler for ASP.NET MVC that will generate automatic jQuery based Javascript and provide a direct way to call MVC Action Methods using a single data annotation. You will no longer have to write custom ajax calls to retrieve data, but just use this library.lkmescom: lk mes com est mon projetMobiLib: MobiLibMoskva.FM: Desktop-?????????? ??? ????????????? ???????????? MOSKVA.FM ? PITER.FM MvcJqGrid: MvcJqGridNetTask: ?????? ?? ???????????????? ? ?????. ?????????? ?.?.Orienteering Maps: OrienteeringMap can be used to organize a collection of orienteering maps.Poken MBDS: Poken MBDSQuake Alert: Quake Alert is a Windows Form application that polls the USGS Website for the latest "big" (5.0+) earthquakes. It runs in the system tray and will alert you to any new earthquakes reported. The window shows you a listing, and allows you to view a map of the incident.Sequencing Application Block: Built with the Ent lib 3.1 application block software factory. Use to generate a sequence of "numbers". without hitting the database. Similar to Oracle® sequencer. Can be used by distributed systems. Relies on caching application block.Simple Extension Framework: Simple Extension Framework is a really simple framework for adding extension points and capabilities to any .NET application or library. Just add a configuration section to your .config file or programmatically use it's API to add extensions, plug-ins, add-ons, add-ins, snap-ins or modules to your code.SoundTouch.NET: The SoundTouch Library is originally written by Olli Parviainen in C++. Although a .NET wrapper library is available, this library aims to be a complete rewrite in C#. This project includes the C# version of the example utility "SoundStretch".SrtFixer: SrtFixer changes srt subtitle of a movie to the desired frame rate. As you may download srt subtitle for your movie which may not accurately be shown. This small tool helps movie fans.Taha Mail 1.0: A Java Web Based Mail

    Read the article

  • ADLDS on Vista SP1

    - by Andy
    I know that Active Directory Lightweight Directory Services (ADLDS) is easily installable on Vista SP2 by the Windows6.0-KB975540-x64.msu update. However, I cant seem to get it working on a Vista SP1 machines I have. Does anyone know how to install ADLDS on Vista SP1 or is it the case that there is nothing like ADLDS / ADAM for Vista SP1? The download page for Windows6.0-KB975540-x64.msu does not clearly define this.

    Read the article

  • Managing MS SQL Server 2005/8 with third-party tools

    - by Craig
    I am trying to access a SQL Server database housed on a ISP. Normally one would simply install an express version of SQL server and use the Management Studio therein. Yeah, not me! Are there any third party tools that will allow me to manage my database? Lightweight ones would be the best but I'm not that picky. :)

    Read the article

  • Multithread http downloader with webui [closed]

    - by kiler129
    I looking for software similar to JDownloader or PyLoad. JD is pretty good but use heavy Java and for now have very weak web interface. PyLoad is awesome, include simple but powerful web-UI but downloading 10 files (10 threads each, so summary it's 100 connections running at around 8MB/s all) consume a lot of cpu - it's whole core for me. Do you know any lightweight alternatives? Aria2c is good for console but I failed to find any good webui, official one is good but after adding more files almost crashes Chrome :)

    Read the article

  • use networkmanager without system tray

    - by Yaakov Belch
    I use the minimal "fast lightweight window manager" (fwlm) which doesn't have a system tray. I need a simple program to manage my WIFI and virtual private netwok connection --- and found the NetworkManager. The problem is that the NetworkManager is a system-tray icon: I cannot see it or click on it in my fwlm windows manager. Hence, I ask: Is there any way to start the NetworkManager directly without using the system tray?

    Read the article

  • What anti-virus & firewall (with IDS) should I use for a windows server machine?

    - by Eran Betzalel
    I want one product to cover for Anti-virus & Firewall purposes. The product should also be lightweight and of course designed for windows server. Any suggestions? Note: I don't need an enterprise solution for the clients - only for the server. BTW, I currently using Symantec SEP, but it's too heavy (during weekly scans) for the server to handle and is not designed for server purposes.

    Read the article

  • Sql Server Managmenet Studio Alternative - Are there any?

    - by JohnM2
    I am looking for lightweight MS SQL Server Managmenet Studio (2005) alternative (open source/freeware is a bonus). Something more like HeidiSQL for MySQL. LINQPad is not an option (although it's great for learning Linq). It can only query database (and has many cons for my needs). I am looking for management/alteration functionality also, not only making queries and viewing the results.

    Read the article

  • Good light debian derivates-distro for VIA C3 processor

    - by stighy
    Hi, i would like to install a good distro on a VIA C3 Samuel system. It would be a light server (with a graphical environment) useful for print server, file server etc. I've tried to install crunchbang linux but it tell me that my processor not support cx8 and cmov instructions. So i'm trying Knoppix.. but i still have some problem ... Do you know other good lightweight distro debian derivates that support via c3 processor ? Thanks

    Read the article

  • Best software for creating icons?

    - by John
    Hi, I'm a developer,but not very good designer.I need a lightweight software for creating icons for my applications. I have a logo of the product and want to make it an icon,please suggest the best software for that. NOTE: I do not need software for creating icons from scratch,but from large image to .ico.Something that will help me. Thanks in advance

    Read the article

  • Windows Media Center Buffering and Asus MyCinema U3100mini

    - by dsimcha
    I'm running an Asus MyCinema U3100mini ATSC on Windows 7 64-bit. When I play live TV in Windows Media Center, it's very choppy and uses 500+ MB of RAM, I'm guessing due to the hard drive buffering functionality. Is there any way to disable the live TV pause buffer completely? If not, can anyone recommend alternative software that: Works with the MyCinema. Is lightweight and not horribly bloated with features I'll never use like Windows Media Center is.

    Read the article

  • Free application which reports that computers are running

    - by Darqer
    I'm searching for an application which reports that the computer is running. I imagine it in the form of two piece software. the first part, some kind of dashboard with list of active IPs, is on the server and awaits for information from remote hosts, the second part will be on clients and it will be reporting that client is working. Do you know something like this, I'm searching for free application that is lightweight and does not require installation.

    Read the article

  • How to create a default association for files with no extension

    - by acidzombie24
    I am using http://www.pnotepad.org/ (i wouldnt mind switching to something else if it lightweight and has most/all features i like which i'll check on a app by app basis) When i create a new tab/file and save it unless i write .txt i get a file with no extention. Which makes it hard to open since i cant double click it (i dont think i can tell win7 to set a default app for files with no extension) How do i make pnotepad save with a .txt when non are specified?

    Read the article

  • Secure linux distro that sends traffic through Tor

    - by gravestone
    I'm looking for a live Linux distro that is secure and preserves my anonymity online. For what I need, Tor seems to do the job – but such software requires configuration that someone who is not knowledgeable in how it works might find difficult. I was looking at 'Lightweight portable security' but it does not specify whether it sends all traffic through Tor. Does anyone know more information about it and/or any other such live Linux distro?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >