Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 39/41 | < Previous Page | 35 36 37 38 39 40 41  | Next Page >

  • Java constructor using generic types

    - by Beer Me
    I'm having a hard time wrapping my head around Java generic types. Here's a simple piece of code that in my mind should work, but I'm obviously doing something wrong. Eclipse reports this error in BreweryList.java: The method breweryMethod() is undefined for the type <T> The idea is to fill a Vector with instances of objects that are a subclass of the Brewery class, so the invocation would be something like: BreweryList breweryList = new BreweryList(BrewerySubClass.class, list); BreweryList.java package com.beerme.test; import java.util.Vector; public class BreweryList<T extends Brewery> extends Vector<T> { public BreweryList(Class<T> c, Object[] j) { super(); for (int i = 0; i < j.length; i++) { T item = c.newInstance(); // breweryMethod() is an instance method // of Brewery, of which <T> is a subclass (right?) c.breweryMethod(); // "The method breweryMethod() is undefined // for the type <T>" } } } Brewery.java package com.beerme.test; public class Brewery { public Brewery() { super(); } protected void breweryMethod() { } } BrewerySubClass.java package com.beerme.test; public class BrewerySubClass extends Brewery { public BrewerySubClass() { super(); } public void brewerySubClassMethod() { } } I'm sure this is a complete-generics-noob question, but I'm stuck. Thanks for any tips!

    Read the article

  • Where to start with map application

    - by rfders
    Hi there, i'm trying to desing a new application which allow user see he/her current location on a custom map (office, university compus, etc). but actually i have a couple of question in my mind (i haven't designed this kind of application before). i'm wondering: How can i draw my own maps, what is the best option for it? there any format that i have to care of, there are any specification about it ? Once i have my custom map. how can i do to mapping a global position system with the local positions ? What are the tricks behing zoom on maps ? just differents layers with more or less informations and those layers changes on users demand ? If a whant to mark some specific points over the map, like a cafeteria, boss's office etc, how can i do that ? Sorry if my questions are too much generics and dumb, but i really need some clues about this topic because i don't have any idea how to design this kind of application as best as possible. and we don't whant to reinvent the wheel. I will appreciate any help that you can provide me in order to desing this application

    Read the article

  • Java Persistence: Cast to something the result of Query.getResultList() ?

    - by GuiSim
    Hey everyone, I'm new to persistence / hibernate and I need your help. Here's the situation. I have a table that contains some stuff. Let's call them Persons. I'd like to get all the entries from the database that are in that table. I have a Person class that is a simple POJO with a property for each column in the table (name, age,..) Here's what I have : Query lQuery = myEntityManager.createQuery("from Person") List<Person> personList = lQuery.getResultList(); However, I get a warning saying that this is an unchecked conversion from List to List<Person> I thought that simply changing the code to Query lQuery = myEntityManager.createQuery("from Person") List<Person> personList = (List<Person>)lQuery.getResultList(); would work.. but it doesn't. Is there a way to do this ? Does persistence allow me to set the return type of the query ? (Through generics maybe ? )

    Read the article

  • Java constructor using generic types

    - by user37903
    I'm having a hard time wrapping my head around Java generic types. Here's a simple piece of code that in my mind should work, but I'm obviously doing something wrong. Eclipse reports this error in BreweryList.java: The method initBreweryFromObject() is undefined for the type <T> The idea is to fill a Vector with instances of objects that are a subclass of the Brewery class, so the invocation would be something like: BreweryList breweryList = new BreweryList(BrewerySubClass.class, list); BreweryList.java package com.beerme.test; import java.util.Vector; public class BreweryList<T extends Brewery> extends Vector<T> { public BreweryList(Class<T> c, Object[] j) { super(); for (int i = 0; i < j.length; i++) { T item = c.newInstance(); // initBreweryFromObject() is an instance method // of Brewery, of which <T> is a subclass (right?) c.initBreweryFromObject(); // "The method initBreweryFromObject() is undefined // for the type <T>" } } } Brewery.java package com.beerme.test; public class Brewery { public Brewery() { super(); } protected void breweryMethod() { } } BrewerySubClass.java package com.beerme.test; public class BrewerySubClass extends Brewery { public BrewerySubClass() { super(); } public void androidMethod() { } } I'm sure this is a complete-generics-noob question, but I'm stuck. Thanks for any tips!

    Read the article

  • Determine if a Range contains a value

    - by Brad Dwyer
    I'm trying to figure out a way to determine if a value falls within a Range in Swift. Basically what I'm trying to do is adapt one of the examples switch statement examples to do something like this: let point = (1, -1) switch point { case let (x, y) where (0..5).contains(x): println("(\(x), \(y)) has an x val between 0 and 5.") default: println("This point has an x val outside 0 and 5.") } As far as I can tell, there isn't any built in way to do what my imaginary .contains method above does. So I tried to extend the Range class. I ended up running into issues with generics though. I can't extend Range<Int> so I had to try to extend Range itself. The closest I got was this but it doesn't work since >= and <= aren't defined for ForwardIndex extension Range { func contains(val:ForwardIndex) -> Bool { return val >= self.startIndex && val <= self.endIndex } } How would I go about adding a .contains method to Range? Or is there a better way to determine whether a value falls within a range? Edit2: This seems to work to extend Range extension Range { func contains(val:T) -> Bool { for x in self { if(x == val) { return true } } return false } } var a = 0..5 a.contains(3) // true a.contains(6) // false a.contains(-5) // false I am very interested in the ~= operator mentioned below though; looking into that now.

    Read the article

  • Generic Singleton Fasade design pattern

    - by Paul
    Hi I try write singleton fasede pattern with generics. I have one problem, how can I call method from generic variable. Something like this: T1 t1 = new T1(); //call method from t1 t1.Method(); In method SingletonFasadeMethod I have compile error: Error 1 'T1' does not contain a definition for 'Method' and no extension method 'Method' accepting a first argument of type 'T1' could be found (are you missing a using directive or an assembly reference?) Any advace? Thank, I am beginner in C#. All code is here: namespace GenericSingletonFasade { public interface IMyInterface { string Method(); } internal class ClassA : IMyInterface { public string Method() { return " Calling MethodA "; } } internal class ClassB : IMyInterface { public string Method() { return " Calling MethodB "; } } internal class ClassC : IMyInterface { public string Method() { return "Calling MethodC"; } } internal class ClassD : IMyInterface { public string Method() { return "Calling MethodD"; } } public class SingletonFasade<T1,T2,T3> where T1 : class,new() where T2 : class,new() where T3 : class,new() { private static T1 t1; private static T2 t2; private static T3 t3; private SingletonFasade() { t1 = new T1(); t2 = new T2(); t3 = new T3(); } class SingletonCreator { static SingletonCreator() { } internal static readonly SingletonFasade<T1,T2,T3> uniqueInstace = new SingletonFasade<T1,T2,T3>(); } public static SingletonFasade<T1,T2,T3> UniqueInstace { get { return SingletonCreator.uniqueInstace; } } public string SingletonFasadeMethod() { //Problem is here return t1.Method() + t2.Method() + t3.Method(); } } }

    Read the article

  • Monads with Join() instead of Bind()

    - by MathematicalOrchid
    Monads are usually explained in turns of return and bind. However, I gather you can also implement bind in terms of join (and fmap?) In programming languages lacking first-class functions, bind is excruciatingly awkward to use. join, on the other hand, looks quite easy. I'm not completely sure I understand how join works, however. Obviously, it has the [Haskell] type join :: Monad m = m (m x) - m x For the list monad, this is trivially and obviously concat. But for a general monad, what, operationally, does this method actually do? I see what it does to the type signatures, but I'm trying to figure out how I'd write something like this in, say, Java or similar. (Actually, that's easy: I wouldn't. Because generics is broken. ;-) But in principle the question still stands...) Oops. It looks like this has been asked before: Monad join function Could somebody sketch out some implementations of common monads using return, fmap and join? (I.e., not mentioning >>= at all.) I think perhaps that might help it to sink in to my dumb brain...

    Read the article

  • MVC3 Custom view engine

    - by eth0
    I have a custom View Engine that derives from WebFormViewEngine. There's a lot of stuff going on in here, mostly caching. I want to be able to use WebFormViewEngine AND RazorViewEngine at the same time, is this possible? Ideally I'd like to do; ViewEngines.Add(new MyViewEngine<WebFormsViewEngine>()); ViewEngines.Add(new MyViewEngine<RazorViewEngine>()); if a .ascx/.aspx/.master file exists then use WebForms, otherwise use Razor is a .cshtml file exists. EDIT: I should of worded my question better. As my custom view engine derives from WebFormViewEngine it obviously uses WebForms, I can't derive from two classes. I can derive from RazorViewEngine but then I'll loose WebForms. I can duplicate my code entirely, derive from RazorViewEngine and edit the views file extensions, etc. but as I said I've got a lot of custom code in my view engine and would be duplicating hundreds of lines. WebFormViewEngine and RazorViewEngine derive from BuildManagerViewEngine which in turn implements IViewEngine. The problem with that is I have to implement methods CreatePartialView() and CreateView() but how would I know what to return (WebForms/Razor?) using generics?

    Read the article

  • Is there such a thing as a MemberExpression that handles a many-to-many relationship?

    - by Jaxidian
    We're trying to make it easy to write strongly-typed code in all areas of our system, so rather than setting var sortColumn = "FirstName" we'd like to say sortOption = (p => p.FirstName). This works great if the sortOption is of type Expression<Func<Person, object>> (we actually use generics in our code but that doesn't matter). However, we run into problems for many-to-many relationships because this notation breaks down. Consider this simple code: internal class Business { public IQueryable<Address> Addresses { get; set; } public string Name { get; set; } } internal class Address { public State MyState { get; set; } } internal class State { public string Abbreviation { get; set; } public int StateID { get; set; } } Is it possible to have this sort of MemberExpression to identify the StateID column off of a business? Again, the purpose of using this is not to return a StateID object, it's to just identify that property off of that entity (for sorting, filtering, and other purposes). It SEEMS to me that there should be some way to do this, even if it's not quite as pretty as foo = business.Addresses.SomeExtension(a => a.State.StateID);. Is this really possible? If more background is needed, take a look at this old question of mine. We've since updated the code significantly, but this should give you the general detailed idea of the context behind this question.

    Read the article

  • A generic Re-usable C# Property Parser utility

    - by Shyam K Pananghat
    This is about a utility i have happened to write which can parse through the properties of a data contracts at runtime using reflection. The input required is a look like XPath string. since this is using reflection, you dont have to add the reference to any of your data contracts thus making pure generic and re- usable.. you can read about this and get the full c# sourcecode here. Property-Parser-A-C-utility-to-retrieve-values-from-any-Net-Data-contracts-at-runtime Now about the doubts which i have about this utility. i am using this utility enormously i many places of my code I am using Regex repetedly inside a recursion method. does this affect the memmory usage or GC collection badly ?do i have to dispose this manually. if yes how ?. The statements like obj.GetType().GetProperty() and obj.GetType().GetField() returns .net "object" which makes difficult or imposible to introduce generics here. Does this cause to have any overheads like boxing ? on an overall, please suggest to make this utility performance efficient and more light weight on memmory

    Read the article

  • CLR via C# 3rd Edition is out

    - by Abhijeet Patel
    Time for some book news update. CLR via C#, 3rd Edition seems to have been out for a little while now. The book was released in early Feb this year, and needless to say my copy is on it’s way. I can barely wait to dig in and chew on the goodies that one of the best technical authors and software professionals I respect has in store. The 2nd edition of the book was an absolute treat and this edition promises to be no less. Here is a brief description of what’s new and updated from the 2nd edition. Part I – CLR Basics Chapter 1-The CLR’s Execution Model Added about discussion about C#’s /optimize and /debug switches and how they relate to each other. Chapter 2-Building, Packaging, Deploying, and Administering Applications and Types Improved discussion about Win32 manifest information and version resource information. Chapter 3-Shared Assemblies and Strongly Named Assemblies Added discussion of TypeForwardedToAttribute and TypeForwardedFromAttribute. Part II – Designing Types Chapter 4-Type Fundamentals No new topics. Chapter 5-Primitive, Reference, and Value Types Enhanced discussion of checked and unchecked code and added discussion of new BigInteger type. Also added discussion of C# 4.0’s dynamic primitive type. Chapter 6-Type and Member Basics No new topics. Chapter 7-Constants and Fields No new topics. Chapter 8-Methods Added discussion of extension methods and partial methods. Chapter 9-Parameters Added discussion of optional/named parameters and implicitly-typed local variables. Chapter 10-Properties Added discussion of automatically-implemented properties, properties and the Visual Studio debugger, object and collection initializers, anonymous types, the System.Tuple type and the ExpandoObject type. Chapter 11-Events Added discussion of events and thread-safety as well as showing a cool extension method to simplify the raising of an event. Chapter 12-Generics Added discussion of delegate and interface generic type argument variance. Chapter 13-Interfaces No new topics. Part III – Essential Types Chapter 14-Chars, Strings, and Working with Text No new topics. Chapter 15-Enums Added coverage of new Enum and Type methods to access enumerated type instances. Chapter 16-Arrays Added new section on initializing array elements. Chapter 17-Delegates Added discussion of using generic delegates to avoid defining new delegate types. Also added discussion of lambda expressions. Chapter 18-Attributes No new topics. Chapter 19-Nullable Value Types Added discussion on performance. Part IV – CLR Facilities Chapter 20-Exception Handling and State Management This chapter has been completely rewritten. It is now about exception handling and state management. It includes discussions of code contracts and constrained execution regions (CERs). It also includes a new section on trade-offs between writing productive code and reliable code. Chapter 21-Automatic Memory Management Added discussion of C#’s fixed state and how it works to pin objects in the heap. Rewrote the code for weak delegates so you can use them with any class that exposes an event (the class doesn’t have to support weak delegates itself). Added discussion on the new ConditionalWeakTable class, GC Collection modes, Full GC notifications, garbage collection modes and latency modes. I also include a new sample showing how your application can receive notifications whenever Generation 0 or 2 collections occur. Chapter 22-CLR Hosting and AppDomains Added discussion of side-by-side support allowing multiple CLRs to be loaded in a single process. Added section on the performance of using MarshalByRefObject-derived types. Substantially rewrote the section on cross-AppDomain communication. Added section on AppDomain Monitoring and first chance exception notifications. Updated the section on the AppDomainManager class. Chapter 23-Assembly Loading and Reflection Added section on how to deploy a single file with dependent assemblies embedded inside it. Added section comparing reflection invoke vs bind/invoke vs bind/create delegate/invoke vs C#’s dynamic type. Chapter 24-Runtime Serialization This is a whole new chapter that was not in the 2nd Edition. Part V – Threading Chapter 25-Threading Basics Whole new chapter motivating why Windows supports threads, thread overhead, CPU trends, NUMA Architectures, the relationship between CLR threads and Windows threads, the Thread class, reasons to use threads, thread scheduling and priorities, foreground thread vs background threads. Chapter 26-Performing Compute-Bound Asynchronous Operations Whole new chapter explaining the CLR’s thread pool. This chapter covers all the new .NET 4.0 constructs including cooperative cancelation, Tasks, the aralle class, parallel language integrated query, timers, how the thread pool manages its threads, cache lines and false sharing. Chapter 27-Performing I/O-Bound Asynchronous Operations Whole new chapter explaining how Windows performs synchronous and asynchronous I/O operations. Then, I go into the CLR’s Asynchronous Programming Model, my AsyncEnumerator class, the APM and exceptions, Applications and their threading models, implementing a service asynchronously, the APM and Compute-bound operations, APM considerations, I/O request priorities, converting the APM to a Task, the event-based Asynchronous Pattern, programming model soup. Chapter 28-Primitive Thread Synchronization Constructs Whole new chapter discusses class libraries and thread safety, primitive user-mode, kernel-mode constructs, and data alignment. Chapter 29-Hybrid Thread Synchronization Constructs Whole new chapter discussion various hybrid constructs such as ManualResetEventSlim, SemaphoreSlim, CountdownEvent, Barrier, ReaderWriterLock(Slim), OneManyResourceLock, Monitor, 3 ways to solve the double-check locking technique, .NET 4.0’s Lazy and LazyInitializer classes, the condition variable pattern, .NET 4.0’s concurrent collection classes, the ReaderWriterGate and SyncGate classes.

    Read the article

  • Goodbye XML&hellip; Hello YAML (part 2)

    - by Brian Genisio's House Of Bilz
    Part 1 After I explained my motivation for using YAML instead of XML for my data, I got a lot of people asking me what type of tooling is available in the .Net space for consuming YAML.  In this post, I will discuss a nice tooling option as well as describe some small modifications to leverage the extremely powerful dynamic capabilities of C# 4.0.  I will be referring to the following YAML file throughout this post Recipe: Title: Macaroni and Cheese Description: My favorite comfort food. Author: Brian Genisio TimeToPrepare: 30 Minutes Ingredients: - Name: Cheese Quantity: 3 Units: cups - Name: Macaroni Quantity: 16 Units: oz Steps: - Number: 1 Description: Cook the macaroni - Number: 2 Description: Melt the cheese - Number: 3 Description: Mix the cooked macaroni with the melted cheese Tooling It turns out that there are several implementations of YAML tools out there.  The neatest one, in my opinion, is YAML for .NET, Visual Studio and Powershell.  It includes a great editor plug-in for Visual Studio as well as YamlCore, which is a parsing engine for .Net.  It is in active development still, but it is certainly enough to get you going with YAML in .Net.  Start by referenceing YamlCore.dll, load your document, and you are on your way.  Here is an example of using the parser to get the title of the Recipe: var yaml = YamlLanguage.FileTo("Data.yaml") as Hashtable; var recipe = yaml["Recipe"] as Hashtable; var title = recipe["Title"] as string; In a similar way, you can access data in the Ingredients set: var yaml = YamlLanguage.FileTo("Data.yaml") as Hashtable; var recipe = yaml["Recipe"] as Hashtable; var ingredients = recipe["Ingredients"] as ArrayList; foreach (Hashtable ingredient in ingredients) { var name = ingredient["Name"] as string; } You may have noticed that YamlCore uses non-generic Hashtables and ArrayLists.  This is because YamlCore was designed to work in all .Net versions, including 1.0.  Everything in the parsed tree is one of two things: Hashtable, ArrayList or Value type (usually String).  This translates well to the YAML structure where everything is either a Map, a Set or a Value.  Taking it further Personally, I really dislike writing code like this.  Years ago, I promised myself to never write the words Hashtable or ArrayList in my .Net code again.  They are ugly, mostly depreciated collections that existed before we got generics in C# 2.0.  Now, especially that we have dynamic capabilities in C# 4.0, we can do a lot better than this.  With a relatively small amount of code, you can wrap the Hashtables and Array lists with a dynamic wrapper (wrapper code at the bottom of this post).  The same code can be re-written to look like this: dynamic doc = YamlDoc.Load("Data.yaml"); var title = doc.Recipe.Title; And dynamic doc = YamlDoc.Load("Data.yaml"); foreach (dynamic ingredient in doc.Recipe.Ingredients) { var name = ingredient.Name; } I significantly prefer this code over the previous.  That’s not all… the magic really happens when we take this concept into WPF.  With a single line of code, you can bind to the data dynamically in the view: DataContext = YamlDoc.Load("Data.yaml"); Then, your XAML is extremely straight-forward (Nothing else.  No static types, no adapter code.  Nothing): <StackPanel> <TextBlock Text="{Binding Recipe.Title}" /> <TextBlock Text="{Binding Recipe.Description}" /> <TextBlock Text="{Binding Recipe.Author}" /> <TextBlock Text="{Binding Recipe.TimeToPrepare}" /> <TextBlock Text="Ingredients:" FontWeight="Bold" /> <ItemsControl ItemsSource="{Binding Recipe.Ingredients}" Margin="10,0,0,0"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Quantity}" /> <TextBlock Text=" " /> <TextBlock Text="{Binding Units}" /> <TextBlock Text=" of " /> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <TextBlock Text="Steps:" FontWeight="Bold" /> <ItemsControl ItemsSource="{Binding Recipe.Steps}" Margin="10,0,0,0"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Number}" /> <TextBlock Text=": " /> <TextBlock Text="{Binding Description}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> This nifty XAML binding trick only works in WPF, unfortunately.  Silverlight handles binding differently, so they don’t support binding to dynamic objects as of late (March 2010).  This, in my opinion, is a major lacking feature in Silverlight and I really hope we will see this feature available to us in Silverlight 4 Release.  (I am not very optimistic for Silverlight 4, but I can hope for the feature in Silverlight 5, can’t I?) Conclusion I still have a few things I want to say about using YAML in the .Net space including de-serialization and using IronRuby for your YAML parser, but this post is hopefully enough to see how easy it is to incorporate YAML documents in your code. Codeplex Site for YAML tools Dynamic wrapper for YamlCore

    Read the article

  • C# async and actors

    - by Alex.Davies
    If you read my last post about async, you might be wondering what drove me to write such odd code in the first place. The short answer is that .NET Demon is written using NAct Actors. Actors are an old idea, which I believe deserve a renaissance under C# 5. The idea is to isolate each stateful object so that only one thread has access to its state at any point in time. That much should be familiar, it's equivalent to traditional lock-based synchronization. The different part is that actors pass "messages" to each other rather than calling a method and waiting for it to return. By doing that, each thread can only ever be holding one lock. This completely eliminates deadlocks, my least favourite concurrency problem. Most people who use actors take this quite literally, and there are plenty of frameworks which help you to create message classes and loops which can receive the messages, inspect what type of message they are, and process them accordingly. But I write C# for a reason. Do I really have to choose between using actors and everything I love about object orientation in C#? Type safety Interfaces Inheritance Generics As it turns out, no. You don't need to choose between messages and method calls. A method call makes a perfectly good message, as long as you don't wait for it to return. This is where asynchonous methods come in. I have used NAct for a while to wrap my objects in a proxy layer. As long as I followed the rule that methods must always return void, NAct queued up the call for later, and immediately released my thread. When I needed to get information out of other actors, I could use EventHandlers and callbacks (continuation passing style, for any CS geeks reading), and NAct would call me back in my isolated thread without blocking the actor that raised the event. Using callbacks looks horrible though. To remind you: m_BuildControl.FilterEnabledForBuilding(    projects,    enabledProjects = m_OutOfDateProjectFinder.FilterNeedsBuilding(        enabledProjects,             newDirtyProjects =             {                 ....... Which is why I'm really happy that NAct now supports async methods. Now, methods are allowed to return Task rather than just void. I can await those methods, and C# 5 will turn the rest of my method into a continuation for me. NAct will run the other method in the other actor's context, but will make sure that when my method resumes, we're back in my context. Neither actor was ever blocked waiting for the other one. Apart from when they were actually busy doing something, they were responsive to concurrent messages from other sources. To be fair, you could use async methods with lock statements to achieve exactly the same thing, but it's ugly. Here's a realistic example of an object that has a queue of data that gets passed to another object to be processed: class QueueProcessor {    private readonly ItemProcessor m_ItemProcessor = ...     private readonly object m_Sync = new object();    private Queue<object> m_DataQueue = ...    private List<object> m_Results = ...     public async Task ProcessOne() {         object data = null;         lock (m_Sync)         {             data = m_DataQueue.Dequeue();         }         var processedData = await m_ItemProcessor.ProcessData(data); lock (m_Sync)         {             m_Results.Add(processedData);         }     } } We needed to write two lock blocks, one to get the data to process, one to store the result. The worrying part is how easily we could have forgotten one of the locks. Compare that to the version using NAct: class QueueProcessorActor : IActor { private readonly ItemProcessor m_ItemProcessor = ... private Queue<object> m_DataQueue = ... private List<object> m_Results = ... public async Task ProcessOne()     {         // We are an actor, it's always thread-safe to access our private fields         var data = m_DataQueue.Dequeue();         var processedData = await m_ItemProcessor.ProcessData(data);         m_Results.Add(processedData);     } } You don't have to explicitly lock anywhere, NAct ensures that your code will only ever run on one thread, because it's an actor. Either way, async is definitely better than traditional synchronous code. Here's a diagram of what a typical synchronous implementation might do: The left side shows what is running on the thread that has the lock required to access the QueueProcessor's data. The red section is where that lock is held, but doesn't need to be. Contrast that with the async version we wrote above: Here, the lock is released in the middle. The QueueProcessor is free to do something else. Most importantly, even if the ItemProcessor sometimes calls the QueueProcessor, they can never deadlock waiting for each other. So I thoroughly recommend you use async for all code that has to wait a while for things. And if you find yourself writing lots of lock statements, think about using actors as well. Using actors and async together really takes the misery out of concurrent programming.

    Read the article

  • Myths about Coding Craftsmanship part 2

    - by tom
    Myth 3: The source of all bad code is inept developers and stupid people When you review code is this what you assume?  Shame on you.  You are probably making assumptions in your code if you are assuming so much already.  Bad code can be the result of any number of causes including but not limited to using dated techniques (like boxing when generics are available), not following standards (“look how he does the spacing between arguments!” or “did he really just name that variable ‘bln_Hello_Cats’?”), being redundant, using properties, methods, or objects in a novel way (like switching on button.Text between “Hello World” and “Hello World “ //clever use of space character… sigh), not following the SOLID principals, hacking around assumptions made in earlier iterations / hacking in features that should be worked into the overall design.  The first two issues, while annoying are pretty easy to spot and can be fixed so easily.  If your coding team is made up of experienced professionals who are passionate about staying current then these shouldn’t be happening.  If you work with a variety of skills, backgrounds, and experience then there will be some of this stuff going on.  If you have an opportunity to mentor such a developer who is receptive to constructive criticism don’t be a jerk; help them and the codebase will improve.  A little patience can improve the codebase, your work environment, and even your perspective. The novelty and redundancy I have encountered has often been the use of creativity when language knowledge was perceived as unavailable or too time consuming.  When developers learn on the job you get a lot of this.  Rather than going to MSDN developers will use what they know.  Depending on the constraints of their assignment hacking together what they know may seem quite practical.  This was not stupid though I often wonder how much time is actually “saved” by hacking.  These issues are often harder to untangle if we ever do.  They can also grow out of control as we write hack after hack to make it work and get back to some development that is satisfying. Hacking upon an existing hack is what I call “feeding the monster”.  Code monsters are anti-patterns and hacks gone wild.  The reason code monsters continue to get bigger is that they keep growing in scope, touching more and more of the application.  This is not the result of dumb developers. It is probably the result of avoiding design, not taking the time to understand the problems or anticipate or communicate the vision of the product.  If our developers don’t understand the purpose of a feature or product how do we expect potential customers to do so? Forethought and organization are often what is missing from bad code.  Developers who do not use the SOLID principals should be encouraged to learn these principals and be given guidance on how to apply them.  The time “saved” by giving hackers room to hack will be made up for and then some. Not as technical debt but as shoddy work that if not replaced will be struggled with again and again.  Bad code is not the result of dumb developers (usually) it is the result of trying to do too much without the proper resources and neglecting the right thing that needs doing with the first thoughtless thing that comes into our heads. Object oriented code is all about relationships between objects.  Coders who believe their coworkers are all fools tend to write objects that are difficult to work with, not eager to explain themselves, and perform erratically and irrationally.  If you constantly find you are surrounded by idiots you may want to ask yourself if you are being unreasonable, if you are being closed minded, of if you have chosen the right profession.  Opening your mind up to the idea that you probably work with rational, well-intentioned people will probably make you a better coder and it might even make you less grumpy.  If you are surrounded by jerks who do not engage in the exchange of ideas who do not care about their customers or the durability of the code you are building together then I suggest you find a new place to work.  Myth 4: Customers don’t care about “beautiful” code Craftsmanship is customer focused because it means that the job was done right, the product will withstand the abuse, modifications, and scrutiny of our customers.  Users can appreciate a predictable timeline for a release, a product delivered on time and on budget, a feature set that does not interfere with the task(s) it is supporting, quick turnarounds on exception messages, self healing issues, and less issues.  These are all hindered by skimping on craftsmanship.  When we write data access and when we write reusable code.   What do you think?  Does bad code come primarily from low IQ individuals?  Do customers care about beautiful code?

    Read the article

  • Using Unity – Part 4

    - by nmarun
    In this part, I’ll be discussing about constructor and property or setter injection. I’ve created a new class – Product3: 1: public class Product3 : IProduct 2: { 3: public string Name { get; set; } 4: [Dependency] 5: public IDistributor Distributor { get; set; } 6: public ILogger Logger { get; set; } 7:  8: public Product3(ILogger logger) 9: { 10: Logger = logger; 11: Name = "Product 1"; 12: } 13:  14: public string WriteProductDetails() 15: { 16: StringBuilder productDetails = new StringBuilder(); 17: productDetails.AppendFormat("{0}<br/>", Name); 18: productDetails.AppendFormat("{0}<br/>", Logger.WriteLog()); 19: productDetails.AppendFormat("{0}<br/>", Distributor.WriteDistributorDetails()); 20: return productDetails.ToString(); 21: } 22: } This version has a property of type IDistributor and takes a constructor parameter of type ILogger. The IDistributor property has a Dependency attribute (Microsoft.Practices.Unity namespace) applied to it. IDistributor and its implementation are shown below: 1: public interface IDistributor 2: { 3: string WriteDistributorDetails(); 4: } 5:  6: public class Distributor : IDistributor 7: { 8: public List<string> DistributorNames = new List<string>(); 9:  10: public Distributor() 11: { 12: DistributorNames.Add("Distributor1"); 13: DistributorNames.Add("Distributor2"); 14: DistributorNames.Add("Distributor3"); 15: DistributorNames.Add("Distributor4"); 16: } 17: public string WriteDistributorDetails() 18: { 19: StringBuilder distributors = new StringBuilder(); 20: for (int i = 0; i < DistributorNames.Count; i++) 21: { 22: distributors.AppendFormat("{0}<br/>", DistributorNames[i]); 23: } 24: return distributors.ToString(); 25: } 26: } ILogger and the FileLogger have the following definition: 1: public interface ILogger 2: { 3: string WriteLog(); 4: } 5:  6: public class FileLogger : ILogger 7: { 8: public string WriteLog() 9: { 10: return string.Format("Type: {0}", GetType()); 11: } 12: } The Unity container creates an instance of the dependent class (the Distributor class) within the scope of the target object (an instance of Product3 class that will be called by doing a Resolve<IProduct>() in the calling code) and assign this dependent object to the attributed property of the target object. To add to it, property injection is a form of optional injection of dependent objects.The dependent object instance is generated before the container returns the target object. Unlike constructor injection, you must apply the appropriate attribute in the target class to initiate property injection. Let’s see how to change the config file to make this work. The first step is to add all the type aliases: 1: <typeAlias alias="Product3" type="ProductModel.Product3, ProductModel"/> 2: <typeAlias alias="ILogger" type="ProductModel.ILogger, ProductModel"/> 3: <typeAlias alias="FileLogger" type="ProductModel.FileLogger, ProductModel"/> 4: <typeAlias alias="IDistributor" type="ProductModel.IDistributor, ProductModel"/> 5: <typeAlias alias="Distributor" type="ProductModel.Distributor, ProductModel"/> Now define mappings for these aliases: 1: <type type="ILogger" mapTo="FileLogger" /> 2: <type type="IDistributor" mapTo="Distributor" /> Next step is to define the constructor and property injection in the config file: 1: <type type="IProduct" mapTo="Product3" name="ComplexProduct"> 2: <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration"> 3: <constructor> 4: <param name="logger" parameterType="ILogger" /> 5: </constructor> 6: <property name="Distributor" propertyType="IDistributor"> 7: <dependency /> 8: </property> 9: </typeConfig> 10: </type> There you see a constructor element that tells there’s a property named ‘logger’ that is of type ILogger. By default, the type of ILogger gets resolved to type FileLogger. There’s also a property named ‘Distributor’ which is of type IDistributor and which will get resolved to type Distributor. On the calling side, I’ve added a new button, whose click event does the following: 1: protected void InjectionButton_Click(object sender, EventArgs e) 2: { 3: unityContainer.RegisterType<IProduct, Product3>(); 4: IProduct product3 = unityContainer.Resolve<IProduct>(); 5: productDetailsLabel.Text = product3.WriteProductDetails(); 6: } This renders the following output: This completes the part for constructor and property injection. In the next blog, I’ll talk about Arrays and Generics. Please see the code used here.

    Read the article

  • In Protobuf-net how can I pass an array of type object with objects of different types inside, knowi

    - by cloudraven
    I am trying to migrate existing code that uses XmlSerializer to protobuf-net due to the increased performance it offers, however I am having problems with this specific case. I have an object[] that includes parameters that are going to be sent to a remote host (sort of a custom mini rpc facility). I know the set of types from which these parameters can be, but I cannot tell in advance in which order they are going to be sent. I have three constraints. The first is that I am running in Compact Framework, so I need something that works there. Second, as I mentioned performance is a big concern (on the serializing side) so I would rather avoid using a lot of reflection there if possible. And the most important is that I care about the order in which this parameters were sent. Using XmlSerializer it was easy just adding XmlInclude, but for fields there is nothing equivalent as far as I know in Protobuf-net. So, is there a way to do this? Here is a simplified example. [Serializable] [XmlInclude(typeof(MyType1)), XmlInclude(typeof(MyType2)), XmlInclude(typeof(MyType3)) public class Message() { public object[] parameters; public Message(object[] parms) { parameters = parms; } } Message m = new Message(new object[] {MyType1(), 33, "test", new MyType3(), new MyType3()}); MemoryStream ms = new MemoryStream(); XmlSerializer xml = new XmlSerializer(typeof(Message)); xml.Serialize(ms,xml); That will just work with XmlSerializer, but if I try to convert it to protobuf-net I will get a "No default encoding for Object" message. The best I came up with is to use generics and [ProtoInclude] as seen in this example. Since I can have different object types within the array this doesn't quite make it. I added a generic List for each potential type and a property with [ProtoIgnore] with type object[] to add them and get them. I have to use reflection when adding them (to know in which array to put each item) which is not desirable and I still can't preserve the ordering as I just extract all the items on each list one by one and put them into a new object[] array on the property get. I wonder if there is a way to accomplish this?

    Read the article

  • Managing a difficult manager

    - by griegs
    I have a situation here at work. We are redeveloping our basic architecture across the entire company. Currently we have the following hierarchy; SQL Database <= Stored Procs not allowed. nHibernate Classes to convert nHibernate into our own objects Web Service <= for all external and [internal] calls. Class to take objects from Web Service and back into our own objects and then… Normal nTier application architecture such as Data Transformation Layer, Business layer etc. Within the database, when we are writing a hierarchy of objects to the database, say for example; Order Person Details Address Product Other We need to serialise the object and save it, in its entirety, to an image field in a table. No attempt has been made to store the objects in their own tables so that we can do useful stuff like report on it. This is an architecture that was implemented [way] before I started and as you can probably appreciate, is a complete nightmare not to mention slow as a wet weekend. We’re not even allowed to have stored procs within SQL server because in my boss’s last job they had a hundred or so and he had a problem identifying them all so therefore all stored procs are the devil. Now the same person that developed the above architecture has developed the new one. It came as no surprise that he’s essentially used the same framework only now it’s using DotNet 3.5 with interfaces and generics. We still have to go through web services, still need to serialise (everything), still not allowed to use stored procs etc. In fact, we’re only barely able to bang two rocks together here. He says to us that the framework is open for discussion but when you discuss it, unless you approve of his design, you are told flatly “No”. He simply won’t listen to any other suggestions. Even when you show him demo applications of his proposed architecture v’s yours and he can see the speed difference, he still won’t take that on board. So I guess my question is, and I know others have experienced the same things out there, how do I get through to someone like this? How do you convince someone to ditch Web Services for internal calls and applications? How do you demonstrate, and make it stick, that stored procs are a better way to go than ad-hoc sql statements? This is killing me. I don’t want to repeat the mistakes of the past and I certainly don’t want to write code that I know is going to be slow and cumbersome. Help!

    Read the article

  • Using Include() with inherited entities problem

    - by Peter Stegnar
    In EF eager loading related entities is easy. But I'm having difficulties including inherited entities when loading data using table-per-type model. This is my model: Entities: ArticleBase (base article entity) ArticleSpecial (inherited from ArticleBase) UserBase (base user entity) UserSpecial (inherited from UserBase) Image Relations are as shown on the image (omitting many columns): In reality my users are always of type UserSpecial, since UserBase is used in another application, thus we can share credentials. That's the only reason I have two separate tables. UserBase table can't be changed in any way shape or form, because the other app would break. Question How am I suppose to load ArticleSpecial with both CreatedBy and EditedBy set, so that both are of type UserSpecial (that defines Image relation)? I've tried (unsuccessfully though) these options: 1. Using lambda expressions: context.ArticleBases .OfType<ArticleSpecial>() .Include("UserCreated.Image") .Include("UserEdited.Image"); In this case the problem is that both CreatedBy and EditedBy are related to UserBase, that doesn't define Image navigation. So I should somehow cast these two to UserSpecial type like: context.ArticleBases .OfType<ArticleSpecial>() .Include("UserCreated<UserSpecial>.Image") .Include("UserEdited<UserSpecial>.Image"); But of course using generics in Include("UserCreated<UserSpecial>.Image") don't work. 2. I have tried using LINQ query var results = from articleSpecial in ctx.ArticleBase.OfType<ArticleSpecial>() join created in ctx.UserBase.OfType<UserSpecial>().Include("Image") on articleSpecial.UserCreated.Id equals created.Id join edited in ctx.UserBase.OfType<UserSpecial>().Include("Image") on articleSpecial.UserEdited.Id equals edited.Id select articleSpecial; In this case I'm only getting ArticleSpecial object instances without related properties being set. I know I should select those somehow, but I don't know how? Select part in my LINQ could be changed to something like select new { articleSpecial, articleSpecial.UserCreated, articleSpecial.UserEdited }; but images are still not loaded into my context. My joins in this case are barely used to filter out articleSpecial results, but they don't load entities into context (I suppose). Can anybody provide any help regarding this problem? I think it's not so uncommon.

    Read the article

  • get_or_create generic relations in Django & python debugging in general

    - by rabidpebble
    I ran the code to create the generically related objects from this demo: http://www.djangoproject.com/documentation/models/generic_relations/ Everything is good intially: >>> bacon.tags.create(tag="fatty") <TaggedItem: fatty> >>> tag, newtag = bacon.tags.get_or_create(tag="fatty") >>> tag <TaggedItem: fatty> >>> newtag False But then the use case that I'm interested in for my app: >>> tag, newtag = bacon.tags.get_or_create(tag="wholesome") Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 123, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 343, in get_or_create raise e IntegrityError: app_taggeditem.content_type_id may not be NULL I tried a bunch of random things after looking at other code: >>> tag, newtag = bacon.tags.get_or_create(tag="wholesome", content_type=TaggedItem) ValueError: Cannot assign "<class 'generics.app.models.TaggedItem'>": "TaggedItem.content_type" must be a "ContentType" instance. or: >>> tag, newtag = bacon.tags.get_or_create(tag="wholesome", content_type=TaggedItem.content_type) InterfaceError: Error binding parameter 3 - probably unsupported type. etc. I'm sure somebody can give me the correct syntax, but the real problem here is that I have no idea what is going on. I have developed in strongly typed languages for over ten years (x86 assembly, C++ and C#) but am new to Python. I find it really difficult to follow what is going on in Python when things like this break. In the languages I mentioned previously it's fairly straightforward to figure things like this out -- check the method signature and check your parameters. Looking at the Django documentation for half an hour left me just as lost. Looking at the source for get_or_create(self, **kwargs) didn't help either since there is no method signature and the code appears very generic. A next step would be to debug the method and try to figure out what is happening, but this seems a bit extreme... I seem to be missing some fundamental operating principle here... what is it? How do I resolve issues like this on my own in the future?

    Read the article

  • Template function as a template argument

    - by Kos
    I've just got confused how to implement something in a generic way in C++. It's a bit convoluted, so let me explain step by step. Consider such code: void a(int) { // do something } void b(int) { // something else } void function1() { a(123); a(456); } void function2() { b(123); b(456); } void test() { function1(); function2(); } It's easily noticable that function1 and function2 do the same, with the only different part being the internal function. Therefore, I want to make function generic to avoid code redundancy. I can do it using function pointers or templates. Let me choose the latter for now. My thinking is that it's better since the compiler will surely be able to inline the functions - am I correct? Can compilers still inline the calls if they are made via function pointers? This is a side-question. OK, back to the original point... A solution with templates: void a(int) { // do something } void b(int) { // something else } template<void (*param)(int) > void function() { param(123); param(456); } void test() { function<a>(); function<b>(); } All OK. But I'm running into a problem: Can I still do that if a and b are generics themselves? template<typename T> void a(T t) { // do something } template<typename T> void b(T t) { // something else } template< ...param... > // ??? void function() { param<SomeType>(someobj); param<AnotherType>(someotherobj); } void test() { function<a>(); function<b>(); } I know that a template parameter can be one of: a type, a template type, a value of a type. None of those seems to cover my situation. My main question is hence: How do I solve that, i.e. define function() in the last example? (Yes, function pointers seem to be a workaround in this exact case - provided they can also be inlined - but I'm looking for a general solution for this class of problems).

    Read the article

  • Any way to allow classes implementing IEntity and downcast to have operator == comparisons?

    - by George Mauer
    Basically here's the issue. All entities in my system are identified by their type and their id. new Customer() { Id = 1} == new Customer() {Id = 1}; new Customer() { Id = 1} != new Customer() {Id = 2}; new Customer() { Id = 1} != new Product() {Id = 1}; Pretty standard scenario. Since all Entities have an Id I define an interface for all entities. public interface IEntity { int Id { get; set;} } And to simplify creation of entities I make public abstract class BaseEntity<T> : where T : IEntity { int Id { get; set;} public static bool operator ==(BaseEntity<T> e1, BaseEntity<T> e2) { if (object.ReferenceEquals(null, e1)) return false; return e1.Equals(e2); } public static bool operator !=(BaseEntity<T> e1, BaseEntity<T> e2) { return !(e1 == e2); } } where Customer and Product are something like public class Customer : BaseEntity<Customer>, IEntity {} public class Product : BaseEntity<Product>, IEntity {} I think this is hunky dory. I think all I have to do is override Equals in each entity (if I'm super clever, I can even override it only once in the BaseEntity) and everything with work. So now I'm expanding my test coverage and find that its not quite so simple! First of all , when downcasting to IEntity and using == the BaseEntity< override is not used. So what's the solution? Is there something else I can do? If not, this is seriously annoying. Upadate It would seem that there is something wrong with my tests - or rather with comparing on generics. Check this out [Test] public void when_created_manually_non_generic() { // PASSES! var e1 = new Terminal() {Id = 1}; var e2 = new Terminal() {Id = 1}; Assert.IsTrue(e1 == e2); } [Test] public void when_created_manually_generic() { // FAILS! GenericCompare(new Terminal() { Id = 1 }, new Terminal() { Id = 1 }); } private void GenericCompare<T>(T e1, T e2) where T : class, IEntity { Assert.IsTrue(e1 == e2); } Whats going on here? This is not as big a problem as I was afraid, but is still quite annoying and a completely unintuitive way for the language to behave. Update Update Ah I get it, the generic implicitly downcasts to IEntity for some reason. I stand by this being unintuitive and potentially problematic for my Domain's consumers as they need to remember that anything happening within a generic method or class needs to be compared with Equals()

    Read the article

  • Is it any loose coupling mechanism in Objective-C + Cocoa like C# delegates or C++Qt signals+slots?

    - by Eye of Hell
    Hello. For a large programs, the standard way to chalenge a complexity is to divide a program code into small objects. Most of the actual programming languages offer this functionality via classes, so is Objective-C. But after source code is separated into small object, the second challenge is to somehow connect them with each over. Standard approaches, supported by most languages are compositon (one object is a member field of another), inheritance, templates (generics) and callbacks. More cryptic techniques include method-level delagates (C#) and signals+slots (C++Qt). I like the delegates / signals idea, since while connecting two objects i can connect individual methods with each over, without objects knowing anything of each over. For C#, it will look like this: var object1 = new CObject1(); var object2 = new CObject2(); object1.SomethingHappened += object2.HandleSomething; In this code, is object1 calls it's SomethingHappened delegate (like a normal method call) the HandleSomething method of object2 will be called. For C++Qt, it will look like this: var object1 = new CObject1(); var object2 = new CObject2(); connect( object1, SIGNAL(SomethingHappened()), object2, SLOT(HandleSomething()) ); The result will be exactly the same. This technique has some advantages and disadvantages, but generally i like it more than interfaces since if program code base grows i can change connections and add new ones without creating tons of interfaces. After examination of Objective-C i havn't found any way to use this technique i like :(. It seems that Objective-C supports message passing perfectly well, but it requres for object1 to have a pointer to object2 in order to pass it a message. If some object needs to be connected to lots of other objects, in Objective-C i will be forced to give him pointers to each of the objects it must be connected. So, the question :). Is it any approach in Objective-C programming that will closely resemble delegate / signal+slot types of connection, not a 'give first object an entire pointer to second object so it can pass a message to it'. Method-level connections are a bit more preferable to me than object-level connection ^_^.

    Read the article

  • Which work process in my company should I Improve first?

    - by shoren
    I've just started to work in a new place, and I see several things they do that I find really terrible, and I want to know if they are indeed so wrong, or I am just too strict. Please let me know if my criticism is in place, and your opinion on which problem is the worst and should be fixed first. The developement is all in Java. 1) Not using svnignore. This means svn stat can't be used, and developers forget to add files and break the build. 2) Generated files go to same folders as committed files. Can't use simple maven clean, have to find them one by one. Maven clean doesn't remove all of them. 3) Not fixing IDE analyze warnings. Analyze code returns about 5,000 warning, of many different kinds. 4) Not following conventions: spring beans names sometimes start with uppercase and sometimes not, ant properties sometimes with underline and sometimes with dots delimiter, etc. 5) Incremental build takes 6 minutes, even when nothing is changed. 6) Developers only use remote debug, and don't know how to run the Tomcat server internally from the IDE. 7) Developers always restart the server after every compilation, instead of dynamically reloading the class and saving the server's state. It takes them at least 10 minutes to start checking any change in the code. 8) Developers only compile from command line. When there are compilation errors, they manually open the file and go the the problematic line. 9) A complete mess in project dependencies. Over 200 open sources are depended on, and no one knows what is indeed needed and why. They do know that not all dependencies are necessary. 10) Mixing Maven and Ant in a way that disables the benefits of both. In one case, even dependency checks are not done by Maven. 11) Not using generics properly. 12) Developers don't use Subversion integration with IDE (Eclipse, Intellij Idea). What do you think? Where should I start? Is any of the things I mentioned not really a problem?

    Read the article

  • C#: System.Collections.Concurrent.ConcurrentQueue vs. Queue

    - by James Michael Hare
    I love new toys, so of course when .NET 4.0 came out I felt like the proverbial kid in the candy store!  Now, some people get all excited about the IDE and it’s new features or about changes to WPF and Silver Light and yes, those are all very fine and grand.  But me, I get all excited about things that tend to affect my life on the backside of development.  That’s why when I heard there were going to be concurrent container implementations in the latest version of .NET I was salivating like Pavlov’s dog at the dinner bell. They seem so simple, really, that one could easily overlook them.  Essentially they are implementations of containers (many that mirror the generic collections, others are new) that have either been optimized with very efficient, limited, or no locking but are still completely thread safe -- and I just had to see what kind of an improvement that would translate into. Since part of my job as a solutions architect here where I work is to help design, develop, and maintain the systems that process tons of requests each second, the thought of extremely efficient thread-safe containers was extremely appealing.  Of course, they also rolled out a whole parallel development framework which I won’t get into in this post but will cover bits and pieces of as time goes by. This time, I was mainly curious as to how well these new concurrent containers would perform compared to areas in our code where we manually synchronize them using lock or some other mechanism.  So I set about to run a processing test with a series of producers and consumers that would be either processing a traditional System.Collections.Generic.Queue or a System.Collection.Concurrent.ConcurrentQueue. Now, I wanted to keep the code as common as possible to make sure that the only variance was the container, so I created a test Producer and a test Consumer.  The test Producer takes an Action<string> delegate which is responsible for taking a string and placing it on whichever queue we’re testing in a thread-safe manner: 1: internal class Producer 2: { 3: public int Iterations { get; set; } 4: public Action<string> ProduceDelegate { get; set; } 5: 6: public void Produce() 7: { 8: for (int i = 0; i < Iterations; i++) 9: { 10: ProduceDelegate(“Hello”); 11: } 12: } 13: } Then likewise, I created a consumer that took a Func<string> that would read from whichever queue we’re testing and return either the string if data exists or null if not.  Then, if the item doesn’t exist, it will do a 10 ms wait before testing again.  Once all the producers are done and join the main thread, a flag will be set in each of the consumers to tell them once the queue is empty they can shut down since no other data is coming: 1: internal class Consumer 2: { 3: public Func<string> ConsumeDelegate { get; set; } 4: public bool HaltWhenEmpty { get; set; } 5: 6: public void Consume() 7: { 8: bool processing = true; 9: 10: while (processing) 11: { 12: string result = ConsumeDelegate(); 13: 14: if(result == null) 15: { 16: if (HaltWhenEmpty) 17: { 18: processing = false; 19: } 20: else 21: { 22: Thread.Sleep(TimeSpan.FromMilliseconds(10)); 23: } 24: } 25: else 26: { 27: DoWork(); // do something non-trivial so consumers lag behind a bit 28: } 29: } 30: } 31: } Okay, now that we’ve done that, we can launch threads of varying numbers using lambdas for each different method of production/consumption.  First let's look at the lambdas for a typical System.Collections.Generics.Queue with locking: 1: // lambda for putting to typical Queue with locking... 2: var productionDelegate = s => 3: { 4: lock (_mutex) 5: { 6: _mutexQueue.Enqueue(s); 7: } 8: }; 9:  10: // and lambda for typical getting from Queue with locking... 11: var consumptionDelegate = () => 12: { 13: lock (_mutex) 14: { 15: if (_mutexQueue.Count > 0) 16: { 17: return _mutexQueue.Dequeue(); 18: } 19: } 20: return null; 21: }; Nothing new or interesting here.  Just typical locks on an internal object instance.  Now let's look at using a ConcurrentQueue from the System.Collections.Concurrent library: 1: // lambda for putting to a ConcurrentQueue, notice it needs no locking! 2: var productionDelegate = s => 3: { 4: _concurrentQueue.Enqueue(s); 5: }; 6:  7: // lambda for getting from a ConcurrentQueue, once again, no locking required. 8: var consumptionDelegate = () => 9: { 10: string s; 11: return _concurrentQueue.TryDequeue(out s) ? s : null; 12: }; So I pass each of these lambdas and the number of producer and consumers threads to launch and take a look at the timing results.  Basically I’m timing from the time all threads start and begin producing/consuming to the time that all threads rejoin.  I won't bore you with the test code, basically it just launches code that creates the producers and consumers and launches them in their own threads, then waits for them all to rejoin.  The following are the timings from the start of all threads to the Join() on all threads completing.  The producers create 10,000,000 items evenly between themselves and then when all producers are done they trigger the consumers to stop once the queue is empty. These are the results in milliseconds from the ordinary Queue with locking: 1: Consumers Producers 1 2 3 Time (ms) 2: ---------- ---------- ------ ------ ------ --------- 3: 1 1 4284 5153 4226 4554.33 4: 10 10 4044 3831 5010 4295.00 5: 100 100 5497 5378 5612 5495.67 6: 1000 1000 24234 25409 27160 25601.00 And the following are the results in milliseconds from the ConcurrentQueue with no locking necessary: 1: Consumers Producers 1 2 3 Time (ms) 2: ---------- ---------- ------ ------ ------ --------- 3: 1 1 3647 3643 3718 3669.33 4: 10 10 2311 2136 2142 2196.33 5: 100 100 2480 2416 2190 2362.00 6: 1000 1000 7289 6897 7061 7082.33 Note that even though obviously 2000 threads is quite extreme, the concurrent queue actually scales really well, whereas the traditional queue with simple locking scales much more poorly. I love the new concurrent collections, they look so much simpler without littering your code with the locking logic, and they perform much better.  All in all, a great new toy to add to your arsenal of multi-threaded processing!

    Read the article

  • C# in Depth, Third Edition by Jon Skeet, Manning Publications Co. Book Review

    - by Compudicted
    Originally posted on: http://geekswithblogs.net/Compudicted/archive/2013/10/24/c-in-depth-third-edition-by-jon-skeet-manning-publications.aspx I started reading this ebook on September 28, 2013, the same day it was sent my way by Manning Publications Co. for review while it still being fresh off the press. So 1st thing – thanks to Manning for this opportunity and a free copy of this must have on every C# developer’s desk book! Several hours ago I finished reading this book (well, except a for a large portion of its quite lengthy appendix). I jumped writing this review right away while still being full of emotions and impressions from reading it thoroughly and running code examples. Before I go any further I would like say that I used to program on various platforms using various languages starting with the Mainframe and ending on Windows, and I gradually shifted toward dealing with databases more than anything, however it happened with me to program in C# 1 a lot when it was first released and then some C# 2 with a big leap in between to C# 5. So my perception and experience reading this book may differ from yours. Also what I want to tell is somewhat funny that back then, knowing some Java and seeing C# 1 released, initially made me drawing a parallel that it is a copycat language, how wrong was I… Interestingly, Jon programs in Java full time, but how little it was mentioned in the book! So more on the book: Be informed, this is not a typical “Recipes”, “Cookbook” or any set of ready solutions, it is rather targeting mature, advanced developers who do not only know how to use a number of features, but are willing to understand how the language is operating “under the hood”. I must state immediately, at the same time I am glad the author did not go into the murky depths of the MSIL, so this is a very welcome decision on covering a modern language as C# for me, thank you Jon! Frankly, not all was that rosy regarding the tone and structure of the book, especially the the first half or so filled me with several negative and positive emotions overpowering each other. To expand more on that, some statements in the book appeared to be bias to me, or filled with pre-justice, it started to look like it had some PR-sole in it, but thankfully this was all gone toward the end of the 1st third of the book. Specifically, the mention on the C# language popularity, Java is the #1 language as per https://sites.google.com/site/pydatalog/pypl/PyPL-PopularitY-of-Programming-Language (many other sources put C at the top which I highly doubt), also many interesting functional languages as Clojure and Groovy appeared and gained huge traction which run on top of Java/JVM whereas C# does not enjoy such a situation. If we want to discuss the popularity in general and say how fast a developer can find a new job that pays well it would be indeed the very Java, C++ or PHP, never C#. Or that phrase on language preference as a personal issue? We choose where to work or we are chosen because of a technology used at a given software shop, not vice versa. The book though it technically very accurate with valid code, concise examples, but I wish the author would give more concrete, real-life examples on where each feature should be used, not how. Another point to realize before you get the book is that it is almost a live book which started to be written when even C# 3 wasn’t around so a lot of ground is covered (nearly half of the book) on the pre-C# 3 feature releases so if you already have a solid background in the previous releases and do not plan to upgrade, perhaps half of the book can be skipped, otherwise this book is surely highly recommended. Alas, for me it was a hard read, most of it. It was not boring (well, only may be two times), it was just hard to grasp some concepts, but do not get me wrong, it did made me pause, on several occasions, and made me read and re-read a page or two. At times I even wondered if I have any IQ at all (LOL). Be prepared to read A LOT on generics, not that they are widely used in the field (I happen to work as a consultant and went thru a lot of code at many places) I can tell my impression is the developers today in best case program using examples found at OpenStack.com. Also unlike the Java world where having the most recent version is nearly mandated by the OSS most companies on the Microsoft platform almost never tempted to upgrade the .Net version very soon and very often. As a side note, I was glad to see code recently that included a nullable variable (myvariable? notation) and this made me smile, besides, I recommended that person this book to expand her knowledge. The good things about this book is that Jon maintains an active forum, prepared code snippets and even a small program (Snippy) that is happy to run the sample code saving you from writing any plumbing code. A tad now on the C# language itself – it sure enjoyed a wonderful road toward perfection and a very high adoption, especially for ASP development. But to me all the recent features that made this statically typed language more dynamic look strange. Don’t we have F#? Which supposed to be the dynamic language? Why do we need to have a hybrid language? Now the developers live their lives in dualism of the static and dynamic variables! And LINQ to SQL, it is covered in depth, but wasn’t it supposed to be dropped? Also it seems that very little is being added, and at a slower pace, e.g. Roslyn will come in late 2014 perhaps, and will be probably the only main feature. Again, it is quite hard to read this book as various chapters, C# versions mentioned every so often only if I only could remember what was covered exactly where! So the fact it has so many jumps/links back and forth I recommend the ebook format to make the navigations easier to perform and I do recommend using software that allows bookmarking, also make sure you have access to plenty of coffee and pizza (hey, you probably know this joke – who a programmer is) ! In terms of closing, if you stuck at C# 1 or 2 level, it is time to embrace the power of C# 5! Finally, to compliment Manning, this book unlike from any other publisher so far, was the only one as well readable (put it formatted) on my tablet as in Adobe Reader on a laptop.

    Read the article

< Previous Page | 35 36 37 38 39 40 41  | Next Page >