.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

TraceListenerCollection is cleared when looping over IEnumerable

Posted By:      Posted Date: September 13, 2010    Points: 0   Category :.NET Framework
I have the following code in a class in a WPF application: In the constructor: foreach( var traceSource in AvailableSources.ToArray() ) traceSource.Listeners.Add( _listener ); Trace.AutoFlush = true; The AvailableSources property: /// <summary> /// Gets the available sources. /// </summary> /// <value>The available sources.</value> public IEnumerable<TraceSource> AvailableSources { get { yield return TraceSources.Network; // app-specific tracesource yield return TraceSources.Persistence; // app-specific tracesource yield return TraceSources.Gui; // app-specific tracesource PresentationTraceSources.Refresh(); yield return PresentationTraceSources.DataBindingSource;  // WPF tracesource yield return PresentationTraceSources.RoutedEventSource;  // WPF tracesource } } If I doesn't use ToArray() on the property AvailableSources in the foreach loop, the Listeners collection will have zero listeners. If I step through the foreach loop, I will at the end (but before hitting the first line of code outside the loop) have 1 listener in each TraceSource' Listeners collection. When I hit the first line after the loop, I get Listeners.Count = 0 on each tracesource. I've used the immediate window in VS.Net to get the current count of the listeners collection and also verified that the hash code of each tracesource instance

View Complete Post

More Related Resource Links

Looping through DataSet in C#


I have the following line of C# code that successfully returns the results of a stored procudure via a DAL:

spParamGetGamesTableAdapter spGG10 = new spParamGetGamesTableAdapter();

I can bind spGG10 to a DataGrid and see the stored procedure query results, so I know everything is good so far.

I want to loop through the spGG10 (DataSet table?) and output each row on a row-by-row basis using a Literal Control. I think I know how do the output part, so...

My question is: How do I access the data in spGG10 and loop through its records? (Also, I am not exactly sure what kind of object spGG10 really is. Is it a table?)

Thanks in advance.

Looping through controls to find reorderlist to set allowreorder


How would I loop through controls on a content page to set allowreorder of all reorderlists to false. Thank you. 

LinQ Syntax of looping a collection


Hi, I would be glad is there is anyone can point/teach me the correct way of iterate a collection in LINQ. I attached part of my coding for reference. I wish to find out the location(s) of an Employee who can also happen to be a Supervisor. My model contains a Many-to-Many relationship between Location and Employee. Thanks in advance


Dim someDataSource = From _e As Employee In _context.Employees
                                  Where _e.Locations = location <---- _e.Locations return a collection 
                                  Select _e.FullName, _e.ID


IEnumerable.Except incorrectly removes duplicates

IEnumerable.Except is expected to receive a second IEnumerable with the elements to be removed from the first. But when the first collection contains duplicates, those are removed too, despite not being present on the second. Check in the following example that 2.3 appears twice on numbers1 but only once on the output. double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 }; double[] numbers2 = { 2.2 }; IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) Console.WriteLine(number); /* This code produces the following output: 2 2.1 2.3 2.4 2.5 */

Serializing objects which implement IEnumerable<>

Hi, I'm trying for long time to serialize an object which contains an object which implements IEnumerable<>. The last object also contains an object which implements IEnumerable<>. The objects strucutre is as followed: [Serializable] public class A { public B _b {get; set; } } [Serializable] public class B : IEnumerable<C> { public List<C> c_items {get; set;} public void Add (C obj){} } [Serializable] public class C : IEnumerable<D> { public List<D> d_items {get; set;} public void Add (D obj){} } [Serializable] public class D { public int Key {get; set;} public int Value {get; set;} } In the code line: A obj = new A(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); I'm getting the exception: unable to generate temporary class (result=1), error CS0030: Cannot convert type 'C' to type 'D'... When I remove the IEnumerable implementation from one of B or C, the serialization works. What as I getting wrong? Any help would be appreciated!

Looping through Excel 2007 tables in SSIS?

Saw the (http://msdn.microsoft.com/en-us/library/ms345182(v=SQL.90).aspx) msdn article on MSDN, however I need to loop through Excel 2007 tables, which is not supported via the .Net Connection.  Is there a way to loop through the 2007 sheets without resorting to a script component?Steve Walker

IEnumerable instead of IList or Collection

hi,Just wondering and see what your opinions are.I usually pass around the layers either a Custom Collection<T> or a Custom ListBase<T>:IList ..I was now wandering if instead of return from a Data Access Layer or biz layer one of those is better to actually just return an IEnumerable<T>.Shall I drop returning all those LIst<T> Collection<T> and use IEnumerable<T> instead?Would that be more flexible?Thanks for any suggestionsThanks for your help

SharePoint 2010 AD FS 2.0 Integration - login works then fails, looping back to the adfs server

Hello, I setup SharePoint 2010 Claims auth with AD FS 2.0 following this post: http://blogs.technet.com/b/speschka/archive/2010/07/30/configuring-sharepoint-2010-and-adfs-v2-end-to-end.aspx.  I have no access to the ADFS server, but I think they followed the steps as outlined.  If I do an iisreset (or just recycle the app pool of the SharePoint site) I can login successfully using the remote credentials.  Also I can under security in SharePoint search for and find users and roles from the remote ADFS server. If I close my browser, open a new browser and go to the site I am prompted to login again (this is fine).  I do, using the same credentials, and the login fails because I am redirected between the SP and ADFS servers until the ADFS server stops the redirecting.  I have been doing some digging and I found this post: http://blogs.technet.com/b/speschka/archive/2010/08/09/setting-the-login-token-expiration-correctly-for-sharepoint-2010-saml-claims-users.aspx, which describes the situation I have in point # 3 at the bottom.  I have tried setting the token time out as low as 1 second but this hasn't helped. I have also, just to see, tried setting all the other lifetime settings to 1 second - but no luck.  Because the initial login works I think the setup is correct, but something is maintaining some state that is causing the loop

There is no ViewData item of type 'IEnumerable' that has the key 'Carrera'.

When running the HttpGet action, it works fine. But when I run the HttpPost action, I recieve the error in the title. Can anyone help me out? Is it because the HttpPost doesn't have a ViewData declared? Thanks for the help.[HttpGet] public ActionResult Crear() { CarreraRepository carreraRepository = new CarreraRepository(); var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre); var carrerasList = new SelectList(carreras, "ID", "Nombre"); ViewData["Carreras"] = carrerasList; Materia materia = new Materia(); return View(materia); } [HttpPost] public ActionResult Crear(Materia materia, FormCollection values) { if (ModelState.IsValid) { repo.Add(materia); repo.Save(); return RedirectToAction("Index"); } return View(materia); }

Ienumerable,ienumerator and iterator Interface in c#

how I used Ienumerable and ienumerator and itreator interface in c# with Wcf I want To used Through Class. I want To used Through C# Plz Give Me A good Example.   Thanks Neha    

Only a single enumeration is supported by this IEnumerable.

I've only seen a few other posts on the internet about this error message, and none of them seem to give an answer that's relevant to Silverlight asynchronous code. I have a data service operation, I call it from a Silverlight client. I know the service operation is returning the desired data, because I have tested the code in a synchronous aspx page load and browsed it with the debugger. However, whether I have the service operation method return an IQueryable or an IEnumerable, I can't iterate through the results in the Silverlight client code - I receive the error in the title of this post. I can't do a foreach, I can't do a for loop, I can't do a ToList, they all give that error. private void on_oppquery(IAsyncResult result) { /*Use dispatcher to ensure that the asynch call returns in the correct thread*/ Dispatcher.BeginInvoke(() => { IEnumerable<opportunity> response = null; try { /*Since this is the first page, we get back the query*/ var query = result.AsyncState as DataContext; /*Get the response of the query*/ response = query.EndExecute<opportunity>(result); /*Enumeration executes the query*/ //THIS BREAKS //response.ToList<opportunity>(); //THIS BREAKS //foreach (opportunity o

IEnumerable Type Casting

Hello Everyone,  The following line is giving me an InvalidCastException when trying to convert to IEnumerable type, even though I have implemented IEnumerable interface.  Return New CountryInfo(CountryCodes(i), CountryNames(i)) (also in bold below)Imports System Imports Gaia.WebWidgets.HtmlFormatting Imports System.Collections.Generic Imports System.Globalization Public Class CountryInfo Implements IEnumerable Property Name As String Property Code As String Public Sub New(ByVal code As String, ByVal name As String) _Code = code _Name = name End Sub Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return CType(Me, IEnumerator) End Function Public Class SearchResult Private ReadOnly _countries As List(Of CountryInfo) Private ReadOnly _query As String Friend Sub New(ByVal countries As List(Of CountryInfo), ByVal query As String) _countries = countries _query = query End Sub Public ReadOnly Property IsEmpty As Boolean Get Return _countries.Count = 0 End Get End Property Public ReadOnly Property Countries As List(Of CountryInfo) Get Return _countries End Get End Property Public Function Bui

Selected value of RadioButtonList inside a formview get cleared on button click.

Hi all,I placed a RadioButtonList inside a Formview control.And from  DataBound event handler of formview ,RadioButtonList is binded to the datasource .Now my problem is after selecting a value from radiobuttonlist and I click any button,the radiobuttonList get unchecked and lose the selected value .How can I avoid this.Please help..

Session objects not cleared as expected, after upgrading to IIS7.5

I've just upgraded my development machine from XP SP3 (IIS5.1) to Win7 x64 (IIS7.5)Since doing this, my app has started to behave differently.  Within it I store users' preferences/access levels using an instance of a class that I store within the Session object.  This class is shown:Public Class UserSessionObject Private _customerID As Integer Private _userPermission As Integer Private _customerPermission As Integer Public Property CustomerID As Integer Get Return _customerID End Get Set(ByVal value As Integer) _customerID = value End Set End Property Public Property UserPermission As Integer Get Return _userPermission End Get Set(ByVal value As Integer) _userPermission = value End Set End Property Public Property CustomerPermission As Integer Get Return _customerPermission End Get Set(ByVal value As Integer) _customerPermission = value End Set End Property Public Sub New(ByVal CustomerID As Integer, ByVal UserPermission As Integer, ByVal CustomerPermission As Integer) _customerID = CustomerID _userPermission = UserPermission _customerPermission = CustomerPermission End Sub End Class My requirement is that on each page request (other than the login page), the application should check that the Session object exists.  The page data is therefore shown based on the values within the session obj

C# socket looping in response

Hi,   I'm getting data from a TCP server that sends bulk data in burst load. Can I use socket available property to loop in receiving data as below ? Or is it equivalent to peeking which is not recommended in winsock ? Thanks in advance and regards Navin --------------------------------------------------------- //to run loop m_bContinue = true;   int nReceivedBytes = 0;   int cntBytesRead = 0;   string m_strData = "";   StringBuilder sbData = new StringBuilder(); //Loop here while   (m_bContinue) { if   (!m_socket.Poll((Constants.SOCKET_POLL_TIMEOUT_MS % 1000) * 1000, SelectMode.SelectRead))   continue;     int cntAvailBytes = m_socket.Available;   if (cntAvailBytes > 0) {   arrBytesData = new byte[cntAvailBytes];   while (cntAvailBytes > 0) {   int nBytesToRead = cntAvailBytes; nReceivedBytes = m_socket.Receive(arrBytesData, nBytesToRead, SocketFlags.None);   if (nReceivedBytes > 0) {   //convert data from byte array to string   string data = System.Text.Encoding.UTF8.GetString(arrBytesData, 0, nReceivedBytes);   sbData.Append(data); cntAvailBytes -= nReceivedBytes;     }//while (cntAvailBytes >0 ) m_strData = sbData.ToString();

How do i create a looping script

How do I create a script where it will loop through a set of WHERE clause.


I want to complete the following code .... what goes after orderby in IEnumerable.
What is the meaning of creating an object for IEnumerable...........
    public IEnumerable<int> GetDistinctValuesSorted()
                List<int> _distinctvalues = cls_list_integers._integerlist.Distinct().ToList<int>();
                IEnumerable<int> _orderedsequence = _distinctvalues.OrderBy(
                return _orderedsequence;


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend