Search Results

Search found 2563 results on 103 pages for 'collections'.

Page 24/103 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • Find top N elements in a Multiset from Google Collections?

    - by dfrankow
    A Google Collections Multiset is a set of elements each of which has a count (i.e. may be present multiple times). I can't tell you how many times I want to do the following Make a histogram (exactly Multiset) Get the top N values from the histogram Examples: top 10 URLs, top 10 tags, ... What is the canonical way to do #2 given a Multiset? Here is a blog post about it, but that code is not quite what I want. First, it returns everything, not just top N. Second, it copies (is it possible to avoid a copy?). Third, I usually want a deterministic sort, i.e. tiebreak if counts are equal.

    Read the article

  • Do entity collections and object sets implement IQueryable<T>?

    - by Chevex
    I am using Entity Framework for the first time and noticed that the entities object returns entity collections. DBEntities db = new DBEntities(); db.Users; //Users is an ObjectSet<User> User user = db.Users.Where(x => x.Username == "test").First(); //Is this getting executed in the SQL or in memory? user.Posts; //Posts is an EntityCollection<Post> Post post = user.Posts.Where(x => x.PostID == "123").First(); //Is this getting executed in the SQL or in memory? Do both ObjectSet and EntityCollection implement IQueryable? I am hoping they do so that I know the queries are getting executed at the data source and not in memory. EDIT: So apparently EntityCollection does not while ObjectSet does. Does that mean I would be better off using this code? DBEntities db = new DBEntities(); User user = db.Users.Where(x => x.Username == "test").First(); //Is this getting executed in the SQL or in memory? Post post = db.Posts.Where(x => (x.PostID == "123")&&(x.Username == user.Username)).First(); // Querying the object set instead of the entity collection. Also, what is the difference between ObjectSet and EntityCollection? Shouldn't they be the same? Thanks in advance!

    Read the article

  • Hibernate - EhCache - Which region to Cache associations/sets/collections ??

    - by lifeisnotfair
    Hi all, I am a newcomer to hibernate. It would be great if someone could comment over the following query that i have: Say i have a parent class and each parent has multiple children. So the mapping file of parent class would be something like: parent.hbm.xml <hibernate-mapping > <class name="org.demo.parent" table="parent" lazy="true"> <cache usage="read-write" region="org.demo.parent"/> <id name="id" column="id" type="integer" length="10"> <generator class="native"> </generator> </id> <property name="name" column="name" type="string" length="50"/> <set name="children" lazy="true"> <cache usage="read-write" region="org.demo.parent.children" /> <key column="parent_id"/> <one-to-many class="org.demo.children"/> </set> </class> </hibernate-mapping> children.hbm.xml <hibernate-mapping > <class name="org.demo.children" table="children" lazy="true"> <cache usage="read-write" region="org.demo.children"/> <id name="id" column="id" type="integer" length="10"> <generator class="native"> </generator> </id> <property name="name" column="name" type="string" length="50"/> <many-to-one name="parent_id" column="parent_id" type="integer" length="10" not-null="true"/> </class> </hibernate-mapping> So for the set children, should we specify the region org.demo.parent.children where it should cache the association or should we use the cache region of org.demo.children where the children would be getting cached. I am using EHCache as the 2nd level cache provider. I tried to search for the answer to this question but couldnt find any answer in this direction. It makes more sense to use org.demo.children but I dont know in which scenarios one should use a separate cache region for associations/sets/collections as in the above case. Kindly provide your inputs also let me know if I am not clear in my question. Thanks all.

    Read the article

  • JasperReports: is it possible to use multiple data sources, or if not, to use collections in paramet

    - by Knut Arne Vedaa
    It seems that the reporting idiom is that a report consist of a single list of items, with some additional data (parameters). Are there ways to include several unrelated lists in a report, or would this go against the idiom to such an extent that a different tool should rather be used to generate the output? Suppose, for instance, you have a list of Persons that lives in a Building, with names, phone numbers and so on. This list would be the main datasource. Additionally, on the same report you want to show various other information about that Building, such as address, number of floors and so on. The number of items in this information might vary between Buildings, so that you cannot simply put it into static parameters, but would need a map or a list. This is of course a contrieved example, but should serve to illustrate the problem. In short: can you use several unrelated lists in a report?

    Read the article

  • How to use second level cache for lazy loaded collections in Hibernate?

    - by Chandru
    Let's say I have two entities, Employee and Skill. Every employee has a set of skills. Now when I load the skills lazily through the Employee instances the cache is not used for skills in different instances of Employee. Let's Consider the following data set. Employee - 1 : Java, PHP Employee - 2 : Java, PHP When I load Employee - 2 after Employee - 1, I do not want hibernate to hit the database to get the skills and instead use the Skill instances already available in cache. Is this possible? If so how? Hibernate Configuration <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">pass</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/cache</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <mapping class="org.cache.models.Employee" /> <mapping class="org.cache.models.Skill" /> </session-factory> The Entities with imports, getters and setters Removed @Entity @Table(name = "employee") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; public Employee() { } @ManyToMany @JoinTable(name = "employee_skills", joinColumns = @JoinColumn(name = "employee_id"), inverseJoinColumns = @JoinColumn(name = "skill_id")) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private List<Skill> skills; } @Entity @Table(name = "skill") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Skill { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; } SQL for Loading the Second Employee and his Skills Hibernate: select employee0_.id as id0_0_, employee0_.name as name0_0_ from employee employee0_ where employee0_.id=? Hibernate: select skills0_.employee_id as employee1_1_, skills0_.skill_id as skill2_1_, skill1_.id as id1_0_, skill1_.name as name1_0_ from employee_skills skills0_ left outer join skill skill1_ on skills0_.skill_id=skill1_.id where skills0_.employee_id=? In that I specifically want to avoid the second query as the first one is unavoidable anyway.

    Read the article

  • Does the chunk of the System.Collections.Concurrent.Partitioner need to be thread safe?

    - by Scott Chamberlain
    I am working with the Parallel libraries in .net 4 and I am creating a Partitioner and the example shown in the MSDN only has a chunk size of 1 (every time a new result is retrieved it hits the data source instead of the local cache. The version I am writing will pull 10000 SQL rows at a time then feed the rows from the cache until it is empty then pull another batch. Each partition in the Partitioner has its own chunk. I know every time I call to the IEnumerator in from the SQL data-source that needs to be thread safe but for use in a Parallel.ForEach do I need to make every call to the cache for the chunking thread safe?

    Read the article

  • Does anyone know what happens if you do not implement iequtalable when using generic collections?

    - by ChloeRadshaw
    I asked a question here : http://stackoverflow.com/questions/2476793/when-to-use-iequatable-and-why about using Iequatable. From the msdn: The IEquatable(T) interface is used by generic collection objects such as Dictionary(TKey, TValue), List(T), and LinkedList(T) when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove. If you dont implement that interface what exactly happens?? Exception / default object equals / ref equals?

    Read the article

  • Expand in linq not loading inner data collections from service.

    - by Kit
    I am seeing odd behavior with service queries! I am using MVVM pattern for a silverlight 3 app on 3.5 framework and Dataservices 1.5. The following code eager loads correctly the parent object and the child heirarchy perfectly IF and ONLY IF I am preloading the data. But I would like to fetch a different set of the parent object (and its child heirarchy) on different button clicks. What I am seeing is that on button click, only the parent object is retrieved, and the child heirarchy contains nothing. Any suggestions? Any ideas how to tackle this? Thanks all. The method: DataServiceQuery serviceQuery = (DataServiceQuery)(from m1 in dbEntities.gis_Region.Expand("gis_RegionValue/gis_Measure") where m1.RegionGuid == new Guid(regionGuid) select m1); serviceQuery.BeginExecute(GetRegionDetailAsyncResult, serviceQuery); The wired Async Result: DataServiceQuery query = (DataServiceQuery)result.AsyncState; gis_Region region = query.EndExecute(result).First();

    Read the article

  • LINQ to Entities question about orderby and null collections.

    - by Chevex
    I am currently developing a forum. I am new to LINQ and EF. In my forum I have a display that shows a list of topics with the most recent topics first. The problem is that "most recent" is relative to the topic's replies. So I don't want to order the list by the topic's posted date, rather I want to order the list by the topic's last reply's posted date. So that topics with newer replies pop back to the top of the list. This is rather simple if I knew that every topic had at least one reply; I would just do this: var topicsQuery = from x in board.Topics orderby x.Replies.Last().PostedDate descending select x; However, in many cases the topic has no replies. In which case I would like to use the topic's posted date instead. Is there a way within my linq query to order by x.PostedDate in the event that the topic has no replies? I'm getting confused by this and any help would be appreciated. With the above query, it breaks on topics with no replies because of the x.Replies.Last() which assumes there are replies. LastOrDefault() doesn't work because I need to access the PostedDate property which also assumes a reply exists. Thanks in advance for any insight.

    Read the article

  • How do you deserialize a collection with child collections?

    - by Stuart Helwig
    I have a collection of custom entity objects one property of which is an ArrayList of byte arrays. The custom entity is serializable and the collection property is marked with the following attributes: [XmlArray("Images"), XmlArrayItem("Image",typeof(byte[]))] So I serialize a collection of these custom entities and pass them to a web service, as a string. The web service receives the string and byte array in tact, The following code then attempts to deserialize the collection - back into custom entities for processing... XmlSerializer ser = new XmlSerializer(typeof(List<myCustomEntity>)); StringReader reader = new StringReader(xmlStringPassedToWS); List<myCustomEntity> entities = (List<myCustomEntity>)ser.Deserialize(reader); foreach (myCustomEntity e in entities) { // ...do some stuff... foreach (myChildCollection c in entities.ChildCollection { // .. do some more stuff.... } } I've checked the XML resulting from the initial serialization and it does contain byte array - the child collection, as does the StringReader built above. After the deserialization process, the resulting collection of custom entites is fine, except that each object in the collection does not contain any items in its child collection. (i.e. it doesn't get to "...do some more stuff..." above. Can someone please explain what I am doing wrong? Is it possible to serialize ArrayLists within a generic collection of custom entities?

    Read the article

  • How to create view model without sorting collections in memory.

    - by Chevex
    I have a view model (below). public class TopicsViewModel { public Topic Topic { get; set; } public Reply LastReply { get; set; } } I want to populate an IQueryable<TopicsViewModel> with values from my IQueryable<Topic> collection and IQueryable<Reply> collection. I do not want to use the attached entity collection (i.e. Topic.Replies) because I only want the last reply for that topic and doing Topic.Replies.Last() loads the entire entity collection in memory and then grabs the last one in the list. I am trying to stay in IQueryable so that the query is executed in the database. I also don't want to foreach through topics and query replyRepository.Replies because looping through IQueryable<Topic> will start the lazy loading. I'd prefer to build one expression and have all the leg work done in the lower layers. I have the following: IQueryable<TopicsViewModel> topicsViewModel = from x in topicRepository.Topics from y in replyRepository.Replies where y.TopicID == x.TopicID orderby y.PostedDate ascending select new TopicsViewModel { Topic = x, LastReply = y }; But this isn't working. Any ideas how I can populate an IQueryable or IEnumerable of TopicsViewModel so that it queries the database and grabs topics and that topic's last reply? I am trying really hard to avoid grabbing all replies related to that topic. I only want to grab the last reply. Thank you for any insight you have to offer.

    Read the article

  • What techniques are available for filtering collections of objects when using zodb?

    - by Omega
    As the title says: What techniques are available for filtering objects when using zodb? The equivalent in SQL terms would be something like filtering results by a date range. Or only returning rows with a particular value set in a column. If I had a series of blog posts and only wanted ones done in the past month, what would I have to do? Is there any way to optimize these kinds of "queries"? My gut tells me iterating over all the objects in a relationship simply to perform a test is less than optimal.

    Read the article

  • Using Reflection.Emit to match existing constructor

    - by yodaj007
    First, here is the C# code and the disassembled IL: public class Program<T> { private List<T> _items; public Program(T x, [Microsoft.Scripting.ParamDictionary] Microsoft.Scripting.IAttributesCollection col) { _items = new List<T>(); _items.Add(x); } } Here is the IL of that constructor: .method public hidebysig specialname rtspecialname instance void .ctor(!T x, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection col) cil managed { .param [2] .custom instance void [Microsoft.Scripting]Microsoft.Scripting.ParamDictionaryAttribute::.ctor() = ( 01 00 00 00 ) // Code size 34 (0x22) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000e: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0013: ldarg.0 IL_0014: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0019: ldarg.1 IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_001f: nop IL_0020: nop IL_0021: ret } // end of method Program`1::.ctor I am trying to understand the IL code by emitting it myself. This is what I have managed to emit: .method public hidebysig specialname rtspecialname instance void .ctor(!T A_1, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection A_2) cil managed { // Code size 34 (0x22) .maxstack 4 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000c: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0011: ldarg.0 IL_0012: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0017: ldarg.s A_1 IL_0019: nop IL_001a: nop IL_001b: nop IL_001c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_0021: ret } // end of method MyType::.ctor There are a few differences that I just can't figure out. I'm really close... How do I take care of the parameter attribute (ParamDictionaryAttribute)? I can't find a 'custom' opcode. Is the .param [2] important? How do I emit that? Why is the C# code stack size 8, while my emitted version is 4? Is this important?

    Read the article

  • Can one aliased Type not be accessed by another?

    - by jdk
    good stuff // ok to alias a List Type using AliasStringList = System.Collections.Generic.List<string>; // and ok to alias a List of Lists like this using AliasListOfStringList1 = System.Collections.Generic.List<System.Collections.Generic.List<string>>; bad stuff // However **error** to alias another alias using AliasListOfStringList2 = System.Collections.Generic.List<AliasStringList>; Produces the compile error The type or namespace name 'AliasStringList' could not be found (are you missing a using directive or an assembly reference?)

    Read the article

  • What is good practice in .NET system architecture design concerning multiple models and aggregates

    - by BuzzBubba
    I'm designing a larger enterprise architecture and I'm in a doubt about how to separate the models and design those. There are several points I'd like suggestions for: - models to define - way to define models Currently my idea is to define: Core (domain) model Repositories to get data to that domain model from a database or other store Business logic model that would contain business logic, validation logic and more specific versions of forms of data retrieval methods View models prepared for specifically formated data output that would be parsed by views of different kind (web, silverlight, etc). For the first model I'm puzzled at what to use and how to define the mode. Should this model entities contain collections and in what form? IList, IEnumerable or IQueryable collections? - I'm thinking of immutable collections which IEnumerable is, but I'd like to avoid huge data collections and to offer my Business logic layer access with LINQ expressions so that query trees get executed at Data level and retrieve only really required data for situations like the one when I'm retrieving a very specific subset of elements amongst thousands or hundreds of thousands. What if I have an item with several thousands of bids? I can't just make an IEnumerable collection of those on the model and then retrieve an item list in some Repository method or even Business model method. Should it be IQueryable so that I actually pass my queries to Repository all the way from the Business logic model layer? Should I just avoid collections in my domain model? Should I void only some collections? Should I separate Domain model and BusinessLogic model or integrate those? Data would be dealt trough repositories which would use Domain model classes. Should repositories be used directly using only classes from domain model like data containers? This is an example of what I had in mind: So, my Domain objects would look like (e.g.) public class Item { public string ItemName { get; set; } public int Price { get; set; } public bool Available { get; set; } private IList<Bid> _bids; public IQueryable<Bid> Bids { get { return _bids.AsQueryable(); } private set { _bids = value; } } public AddNewBid(Bid newBid) { _bids.Add(new Bid {.... } } Where Bid would be defined as a normal class. Repositories would be defined as data retrieval factories and used to get data into another (Business logic) model which would again be used to get data to ViewModels which would then be rendered by different consumers. I would define IQueryable interfaces for all aggregating collections to get flexibility and minimize data retrieved from real data store. Or should I make Domain Model "anemic" with pure data store entities and all collections define for business logic model? One of the most important questions is, where to have IQueryable typed collections? - All the way from Repositories to Business model or not at all and expose only solid IList and IEnumerable from Repositories and deal with more specific queries inside Business model, but have more finer grained methods for data retrieval within Repositories. So, what do you think? Have any suggestions?

    Read the article

  • When Clearing an ObservableCollection, There are No Items in e.OldItems

    - by cplotts
    I have something here that is really catching me off guard. I have an ObservableCollection of T that is filled with items. I also have an event handler attached to the CollectionChanged event. When you Clear the collection it causes an CollectionChanged event with e.Action set to NotifyCollectionChangedAction.Reset. Ok, that's normal. But what is weird is that neither e.OldItems or e.NewItems has anything in it. I would expect e.OldItems to be filled with all items that were removed from the collection. Has anyone else seen this? And if so, how have they gotten around it? Some background: I am using the CollectionChanged event to attach and detach from another event and thus if I don't get any items in e.OldItems ... I won't be able to detach from that event. CLARIFICATION: I do know that the documentation doesn't outright state that it has to behave this way. But for every other action, it is notifying me of what it has done. So, my assumption is that it would tell me ... in the case of Clear/Reset as well. Below is the sample code if you wish to reproduce it yourself. First off the xaml: <Window x:Class="ObservableCollection.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" > <StackPanel> <Button x:Name="addButton" Content="Add" Width="100" Height="25" Margin="10" Click="addButton_Click"/> <Button x:Name="moveButton" Content="Move" Width="100" Height="25" Margin="10" Click="moveButton_Click"/> <Button x:Name="removeButton" Content="Remove" Width="100" Height="25" Margin="10" Click="removeButton_Click"/> <Button x:Name="replaceButton" Content="Replace" Width="100" Height="25" Margin="10" Click="replaceButton_Click"/> <Button x:Name="resetButton" Content="Reset" Width="100" Height="25" Margin="10" Click="resetButton_Click"/> </StackPanel> </Window> Next, the code behind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace ObservableCollection { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); _integerObservableCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_integerObservableCollection_CollectionChanged); } private void _integerObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Move: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Replace: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: break; default: break; } } private void addButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Add(25); } private void moveButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Move(0, 19); } private void removeButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.RemoveAt(0); } private void replaceButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection[0] = 50; } private void resetButton_Click(object sender, RoutedEventArgs e) { _integerObservableCollection.Clear(); } private ObservableCollection<int> _integerObservableCollection = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; } }

    Read the article

  • Left Join in Subsonic 3

    - by user303187
    I'm trying to do a left join in subsonic 3 using linq but it doesn't seem to work, I get a big error. var post = from p in Post.All() join q in Quote.All() on p.ID equals q.PostID into pq where p.ID == id.Value from qt in pq.DefaultIfEmpty() select new {p, qt}; I'm using subsonic 3, latest GIT version from Rob, but I'm getting an error, see below, when I try a left join. I have searched but I didn't found any solution. Can anyone explain to me why the error and how to fix it? Thanks Expression of type 'System.Collections.Generic.IEnumerable1[GetAQuote.Post]' cannot be used for parameter of type 'System.Linq.IQueryable1[GetAQuote.Post]' of method 'System.Linq.IQueryable1[<>f__AnonymousType221[GetAQuote.Post], System.Collections.Generic.IEnumerable1%5BGetAQuote.Quote%5D, System.Linq.Expressions.Expression1[System.Func2%5BGetAQuote.Post,System.Int32%5D%5D, System.Linq.Expressions.Expression1[System.Func2%5BGetAQuote.Quote,System.Int32%5D%5D, System.Linq.Expressions.Expression1[System.Func3%5BGetAQuote.Post,System.Collections.Generic.IEnumerable1[GetAQuote.Quote],<>f__AnonymousType22%5BGetAQuote.Post,System.Collections.Generic.IEnumerable1%5BGetAQuote.Quote%5D%5D%5D%5D"GetAQuote.Post,System.Collections.Generic.IEnumerable1[GetAQuote.Quote]]] GroupJoin[Post,Quote,Int32,<f__AnonymousType22'`

    Read the article

  • Why enumerator structs are a really bad idea

    - by Simon Cooper
    If you've ever poked around the .NET class libraries in Reflector, I'm sure you would have noticed that the generic collection classes all have implementations of their IEnumerator as a struct rather than a class. As you will see, this design decision has some rather unfortunate side effects... As is generally known in the .NET world, mutable structs are a Very Bad Idea; and there are several other blogs around explaining this (Eric Lippert's blog post explains the problem quite well). In the BCL, the generic collection enumerators are all mutable structs, as they need to keep track of where they are in the collection. This bit me quite hard when I was coding a wrapper around a LinkedList<int>.Enumerator. It boils down to this code: sealed class EnumeratorWrapper : IEnumerator<int> { private readonly LinkedList<int>.Enumerator m_Enumerator; public EnumeratorWrapper(LinkedList<int> linkedList) { m_Enumerator = linkedList.GetEnumerator(); } public int Current { get { return m_Enumerator.Current; } } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Reset() { ((System.Collections.IEnumerator)m_Enumerator).Reset(); } public void Dispose() { m_Enumerator.Dispose(); } } The key line here is the MoveNext method. When I initially coded this, I thought that the call to m_Enumerator.MoveNext() would alter the enumerator state in the m_Enumerator class variable and so the enumeration would proceed in an orderly fashion through the collection. However, when I ran this code it went into an infinite loop - the m_Enumerator.MoveNext() call wasn't actually changing the state in the m_Enumerator variable at all, and my code was looping forever on the first collection element. It was only after disassembling that method that I found out what was going on The MoveNext method above results in the following IL: .method public hidebysig newslot virtual final instance bool MoveNext() cil managed { .maxstack 1 .locals init ( [0] bool CS$1$0000, [1] valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator CS$0$0001) L_0000: nop L_0001: ldarg.0 L_0002: ldfld valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator EnumeratorWrapper::m_Enumerator L_0007: stloc.1 L_0008: ldloca.s CS$0$0001 L_000a: call instance bool [System]System.Collections.Generic.LinkedList`1/Enumerator::MoveNext() L_000f: stloc.0 L_0010: br.s L_0012 L_0012: ldloc.0 L_0013: ret } Here, the important line is 0002 - m_Enumerator is accessed using the ldfld operator, which does the following: Finds the value of a field in the object whose reference is currently on the evaluation stack. So, what the MoveNext method is doing is the following: public bool MoveNext() { LinkedList<int>.Enumerator CS$0$0001 = this.m_Enumerator; bool CS$1$0000 = CS$0$0001.MoveNext(); return CS$1$0000; } The enumerator instance being modified by the call to MoveNext is the one stored in the CS$0$0001 variable on the stack, and not the one in the EnumeratorWrapper class instance. Hence why the state of m_Enumerator wasn't getting updated. Hmm, ok. Well, why is it doing this? If you have a read of Eric Lippert's blog post about this issue, you'll notice he quotes a few sections of the C# spec. In particular, 7.5.4: ...if the field is readonly and the reference occurs outside an instance constructor of the class in which the field is declared, then the result is a value, namely the value of the field I in the object referenced by E. And my m_Enumerator field is readonly! Indeed, if I remove the readonly from the class variable then the problem goes away, and the code works as expected. The IL confirms this: .method public hidebysig newslot virtual final instance bool MoveNext() cil managed { .maxstack 1 .locals init ( [0] bool CS$1$0000) L_0000: nop L_0001: ldarg.0 L_0002: ldflda valuetype [System]System.Collections.Generic.LinkedList`1/Enumerator EnumeratorWrapper::m_Enumerator L_0007: call instance bool [System]System.Collections.Generic.LinkedList`1/Enumerator::MoveNext() L_000c: stloc.0 L_000d: br.s L_000f L_000f: ldloc.0 L_0010: ret } Notice on line 0002, instead of the ldfld we had before, we've got a ldflda, which does this: Finds the address of a field in the object whose reference is currently on the evaluation stack. Instead of loading the value, we're loading the address of the m_Enumerator field. So now the call to MoveNext modifies the enumerator stored in the class rather than on the stack, and everything works as expected. Previously, I had thought enumerator structs were an odd but interesting feature of the BCL that I had used in the past to do linked list slices. However, effects like this only underline how dangerous mutable structs are, and I'm at a loss to explain why the enumerators were implemented as structs in the first place. (interestingly, the SortedList<TKey, TValue> enumerator is a struct but is private, which makes it even more odd - the only way it can be accessed is as a boxed IEnumerator!). I would love to hear people's theories as to why the enumerators are implemented in such a fashion. And bonus points if you can explain why LinkedList<int>.Enumerator.Reset is an explicit implementation but Dispose is implicit... Note to self: never ever ever code a mutable struct.

    Read the article

  • Timeout reading verity collection - CF8

    - by Gary
    For a long time now I've been having a problem with using the verity search service bundled with ColdFusion 8. The issue is with timeout errors occurring when perfoming any operation on a collection. It's intermittent, and usually occurs after a few operations have been successfully performed. For instance: If I'm adding records to a collection the first, say 15 records, will go through with no problems, but all subsequent records will timeout until the service is rebooted. I'm on a shared server, Windows 2008, 64bit as far as I know. The error I receive is: "An error occurred while performing an operation in the Search Engine library. Error reading collection information.: com.verity.api.administration.ConfigurationException: java.io.IOException: Read timed out" Having spoken to my hosting company, and after doing some research, it's been suggested that the number of collections on a server may cause this issue. I've reduced the amount of collections I use, and there are currently 39 collections on the server. As I'm on a shared server, I have no control over how many collections other customers use, however I've read that the limit is 128 collections, so I don't see why 39 should cause it to become unusable. The collections aren't big, there's maybe around 5,000 records between all of them. Any ideas?

    Read the article

  • Getting the type of an array of T, without specifying T - Type.GetType("T[]")

    - by Merlyn Morgan-Graham
    I am trying to create a type that refers to an array of a generic type, without specifying the generic type. That is, I would like to do the equivalent of Type.GetType("T[]"). I already know how to do this with a non-array type. E.g. Type.GetType("System.Collections.Generic.IEnumerable`1") // or typeof(IEnumerable<>) Here's some sample code that reproduces the problem. using System; using System.Collections.Generic; public class Program { public static void SomeFunc<T>(IEnumerable<T> collection) { } public static void SomeArrayFunc<T>(T[] collection) { } static void Main(string[] args) { Action<Type> printType = t => Console.WriteLine(t != null ? t.ToString() : "(null)"); Action<string> printFirstParameterType = methodName => printType( typeof(Program).GetMethod(methodName).GetParameters()[0].ParameterType ); printFirstParameterType("SomeFunc"); printFirstParameterType("SomeArrayFunc"); var iEnumerableT = Type.GetType("System.Collections.Generic.IEnumerable`1"); printType(iEnumerableT); var iEnumerableTFromTypeof = typeof(IEnumerable<>); printType(iEnumerableTFromTypeof); var arrayOfT = Type.GetType("T[]"); printType(arrayOfT); // Prints "(null)" // ... not even sure where to start for typeof(T[]) } } The output is: System.Collections.Generic.IEnumerable`1[T] T[] System.Collections.Generic.IEnumerable`1[T] System.Collections.Generic.IEnumerable`1[T] (null) I'd like to correct that last "(null)". This will be used to get an overload of a function via reflections by specifying the method signature: var someMethod = someType.GetMethod("MethodName", new[] { typeOfArrayOfT }); // ... call someMethod.MakeGenericMethod some time later I've already gotten my code mostly working by filtering the result of GetMethods(), so this is more of an exercise in knowledge and understanding.

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >