Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
G

Gideon Engelberth

@Gideon Engelberth
About
Posts
316
Topics
5
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Getting a Generic Collection from a Generic Collection C# Linq
    G Gideon Engelberth

    It is not quite clear to me what you are trying to do. In the first way, you will end up with studentsubjectCollection equal to the subject collection of the last item in studentsColl. In the second, you are getting the student collection, but not using it and instead pulling from another collection all together. Your final approach looks like it returns an IEnumerable<StudentSubjectCollection>. If you want to flatten these collections into a single sequence, I would direct you to the SelectMany method. When using the query syntax, this is what is called when you have multiple from statements, like so:

    //assumes StudentSubjectCollection has a constructor that
    //takes IEnumerable<StudentSubjectCollection>
    var studentSubjectColl = new StudentSubjectCollection(
    from stu in GetAllStudentCollection()
    from subj in stu.StudentSubjectCollection
    select subj);

    PS: Next time use the 'code block' button to preserve formatting in your code.

    LINQ csharp question linq

  • How To Test If Linq Query Returned Results
    G Gideon Engelberth

    If all you are doing is checking for any result, using query.Any() would be better than query.Count() since Any will stop after one item instead of always iterating the whole sequence.

    LINQ question csharp database linq tutorial

  • Namespace importing at project level question
    G Gideon Engelberth

    As far as the performance question, importing extra namespaces at the project level *may* affect the performance of the compiler *slightly*, but it will not affect the runtime performance of your program/library at all. By the time the IL is run, all calls are performed against fully resolved types/functions regardless of your imports.

    Visual Basic visual-studio performance question

  • struct and class
    G Gideon Engelberth

    That's an interesting hypothetical world. In the real world, if I do this:

    static void Main(string[] args)
    {
    List<int> items = new List<int>(new int[] { 1, 2, 3, 4, 5, 1, 2, 3, 4 });

    List<int> nextIndices = new List<int>();
    try
    {
        for (int i = 0; i < items.Count() - 1; i++)
        {
    
            nextIndices.Add(FindIndexAfter(items, i, toMatch => toMatch == items\[i\]));
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    
    for (int j = 0; j < nextIndices.Count(); j++)
    {
        Console.WriteLine(nextIndices\[j\]);
    }
    
    Console.WriteLine("Program complete...");
    Console.ReadKey();
    

    }

    static int FindIndexAfter<T>(List<T> items, int startIndex, Func<T, bool> predicate)
    {
    if (startIndex < 0)
    throw new ArgumentOutOfRangeException("startIndex",
    "Start index cannot be negative.");
    if (startIndex >= items.Count())
    throw new ArgumentOutOfRangeException("startIndex",
    "Start index must be less than the number of items");
    startIndex++;
    while (startIndex < items.Count())
    {
    if (predicate(items[startIndex]))
    return startIndex;
    startIndex++;
    }

    return -1;
    

    }

    I print:

    5
    6
    7
    8
    -1
    -1
    -1
    -1
    Program Complete

    Passing startIndex as ref (which is close to what you are suggesting as the default), I get this:

    1
    3
    5
    7
    Program Complete

    Since structs are just immutable classes, you now also return by reference, which would mean that you would be filling the list with references to variable i instead of the values returned by the function. I'm not going to try to simulate that sort of return, but I'm pretty sure you would end up with a list filled with items.Count() when you were done. So, now you either have to invent some "return by value" notation or do something like return new int(startIndex); Along the same line, you also now only have assignment by reference. Which means that

    int i = 1;
    int j = i;
    j++;
    Console.WriteLine(i);

    now prints 2 instead of 1. Again, you would need some new syntax to specify "assign by value" instead of by reference. All in all, I just don't think "structs are just immutable classes" (and the default pass-by-reference that comes from it) would actuall

    C#

  • struct and class
    G Gideon Engelberth

    I'm afraid your answer is also wrong. Structs are not forced to be stack allocated. The runtime simply chooses to use the stack in a limited set of circumstances just because it can. However, your statement about passing by value instead of reference is correct and points to the real distinction between structs and classes.

    C#

  • Relationship of C# Version to .NET Version
    G Gideon Engelberth

    3.0 and 3.5 were additive releases to the 2.0 framework that also included some service packs to 2.0. However, The 4.0 framework is a completely different version than the 2.0 framework. Just having the 4.0 framework does not imply that the 2.0 framework is present.

    .NET (Core and Framework) csharp asp-net dotnet question announcement

  • Optimising part of a code thats bulky
    G Gideon Engelberth

    Well, lets see what's in common between your three methods. Everything is the same except for the address you read and which ItemsControl you are filling. If you combined those two things into a separate class, you could simplify the form code. The class would look something like this:

    public class FeedReader
    {
    FeedReader(string address, ItemsControl target)
    {
    _address = address;
    _target = target;
    }

    private string \_address;
    private ItemsControl \_target;
    
    public void LoadFeed()
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(\_address));
        request.BeginGetResponse(new AsyncCallback(ResponseHandler), request);
    }
    
    private void ResponseHandler(IAsyncResult asyncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
    
        if (response.StatusCode == HttpStatusCode.OK)
        {
            XmlReader reader = XmlReader.Create(response.GetResponseStream());
            SyndicationFeed newFeed = SyndicationFeed.Load(reader);
            \_target.Dispatcher.BeginInvoke(delegate
            {
                \_target.ItemsSource = newFeed.Items;
            });
    
        }
    }
    

    }

    And the calling code could then be:

    public NewsFeed()
    {
    InitializeComponent();
    SupportedOrientations = SupportedPageOrientation.Portrait;
    Loaded += new RoutedEventHandler(MainPage_Loaded);

    PageTransitionList.Completed += new EventHandler(PageTransitionList\_Completed);
    
    // Set the data context of the listbox control to the sample data
    //DataContext = new MainViewModel();
    
    //////////////////////////////
    ///// Here's the changes /////
    //////////////////////////////
    FeedReader bbc = new FeedReader("http://www.pchelpforum.com/external.php", ListBbc);
    FeedReader dailyMail = new FeedReader("http://www.dailymail.co.uk/home/index.rss", ListDailyMail);
    FeedReader guardian = new FeedReader("http://www.guardian.co.uk/tv-and-radio/rss", ListGuardian);
    
    //just call this, no other routines needed for updating.
    //all updates are taken care of by the FeedReader class methods.
    bbc.LoadFeed();
    dailyMail.LoadFeed();
    guardian.LoadFeed();
    
    //////////////////////////////
    //////////////////////////////
    //////////////////////////////
    

    }

    C# csharp php database com xml

  • Custom Collection with Extension method, linq Support [modified]
    G Gideon Engelberth

    If all you want to do is raise an event, you should probably just use ObservableCollection, which does raise events on add/insert, remove, and setting items. The Remove(T item) will call the protected overridable RemoveItem(int index) after figuring out the proper index, that's why only one is overridable.

    .NET (Core and Framework) help csharp database linq tutorial

  • Reguler expression [modified]
    G Gideon Engelberth

    To make a group optional, simply append the ? character to the group. This should do the trick: @"(!(?<jobid>.*?),)?(.*)(;(?<field1>.*?)/)?(.*)(:(?<field2>.*?)/)?(.*)"

    C# regex help

  • Custom Collection with Extension method, linq Support [modified]
    G Gideon Engelberth

    It sounds like you want to inherit from Collection(Of T) or ObservableCollection(Of T) (Note that the page is for .NET 4. ObservableCollection is in the WindowsBase assembly in .NET 3.5)

    .NET (Core and Framework) help csharp database linq tutorial

  • Pipes and Files - making it work
    G Gideon Engelberth

    We have a pair of programs using named pipes with a .NET server app and a native (Delphi, not C++, but still native) client app, so I know this is possible. During development, the programs ran on different machines and the required step to let the programs talk across different users was to use the NamedPipeServerStream overload that took a PipeSecurity. It ended up something like this (namespaces avoided for brevity):

    Dim ps As PipeSecurity
    ps.AddAccessRule(New PipeAccessRule("Everyone", PipeAccessRights.FullControl,
    AccessControlType.Allow))
    Dim New NamedPipeServerStream("PipeName", ..., ps)

    As I recall, the problem was configuring the security of the pipe to allow users from another computer to connect.

    Visual Basic question database sysadmin csharp c++

  • How does CLR differentiates between value and reference types
    G Gideon Engelberth

    Rags1512 wrote:

    So, how does CLR differentiate between the two and stores the value type on Stack and reference types on Heap?

    That value types are always on the stack and reference types are always on the heap is a common misconception. The distinction between value types and reference types is not where they are allocated (stack vs. heap), the difference is how they are passed to functions and assignment. Value types are passed by value. Reference types are passed by reference. An article discussing this can be found here

    Rags1512 wrote:

    we know everything in .Net is derived from System.Object, even value and reference types.

    Also, not quite true. See this article for a good explanation.

    C# question csharp database dotnet data-structures

  • Group By
    G Gideon Engelberth

    You could create a custom IEqualityComparer that uses the Equals method to do "near" comparisons instead of the typical meaning of equals. The comparer could keep some state to know which points have already been added, and group new points as "equal" to other "nearby" points. Something like this could get you started:

    Public Class NearEqualityComparer
    Implements IEqualityComparer(Of CustomPoint)

    Public Sub New(ByVal xRange As Integer, ByVal yRange As Integer)
        \_xRange = xRange
        \_yRange = yRange
    End Sub
    
    Private \_xRange As Integer
    Private \_yRange As Integer
    Private \_groups As New List(Of HashSet(Of CustomPoint))
    
    Public Overloads Function Equals(ByVal x As CustomPoint, ByVal y As CustomPoint) As Boolean \_
      Implements System.Collections.Generic.IEqualityComparer(Of CustomPoint).Equals
        Return FindOrCreateGroup(x) Is FindOrCreateGroup(y)
    End Function
    
    Public Overloads Function GetHashCode(ByVal obj As CustomPoint) As Integer \_
      Implements System.Collections.Generic.IEqualityComparer(Of CustomPoint).GetHashCode
        'always return the same hash code to let Equals do the work
        Return 1
    End Function
    
    Private Function PointNearGroup(ByVal newPoint As CustomPoint, \_
                                    ByVal group As IEnumerable(Of CustomPoint)) As Boolean
        Return group.Any(Function(oldPoint) Math.Abs(newPoint.X - oldPoint.X) <= \_xRange AndAlso \_
                                            Math.Abs(newPoint.Y - oldPoint.Y) <= \_yRange)
    End Function
    
    Private Function FindOrCreateGroup(ByVal point As CustomPoint) As HashSet(Of CustomPoint)
        Dim matchingGroup = (From g In \_groups \_
                             Where PointNearGroup(point, g)).FirstOrDefault()
    
        If matchingGroup Is Nothing Then
            matchingGroup = New HashSet(Of CustomPoint)()
            \_groups.Add(matchingGroup)
        End If
        matchingGroup.Add(point)
        Return matchingGroup
    End Function
    

    End Class

    This will not catch certain cases where you may have two groups that are not connected at first, but a later row connects them through a set of points. (In fact, that may not be possible with the framework GroupBy, since I do not know of any way to tell it to merge groups.) However, it should at least give you an idea of how this might work. And in actuality, this ends up doing all the work that GroupBy is doing anyway, so you do not really gain much

    LINQ question

  • Modify Collection using LINQ
    G Gideon Engelberth

    LINQ is not designed for that sort of thing. LINQ is designed to be "functional" in that it aims to provide methods that do not affect the state from which they are queried. You will need to do a for loop yourself to do this.

    C# question tutorial csharp database linq

  • Generic event?
    G Gideon Engelberth

    I had assumed you had a set of classes since generics would not accept an enum value as the type parameter (since it is a constant and not a type). You could still take the approach of letting the handlers receive all events and only process the ones they care about. Something like:

    void PacketProcessor(object sender, PacketEventArgs e)
    {
    if (e.PacketType != Packets.SomePacket) return;

    //do processing on SomePacket data here
    

    }

    This has the advantage of making it obvious to the later reader of the code which packet is being handled by this function, but has the disadvantage all packet handlers will get called for all packets.

    C# csharp visual-studio question learning

  • Generic event?
    G Gideon Engelberth

    My assumption is that the answer for this is that you cannot have a generic event for the same reason you cannot have a generic field in a non-generic class (or of a generic type that is not a type parameter for the class containing the field). If this was allowed, your class would have to vary in size depending on how many different events were used by external code, which of course is not allowed. The best option that comes to mind is making all of the packet classes can inherit from some base packet class. Then you can make the event use that base class and have the handlers only process packets of the expected type.

    C# csharp visual-studio question learning

  • Weird error that only happens sometimes..
    G Gideon Engelberth

    Just on a hunch, are you using the "default form instance" facility that VB.NET provides to help with upgrading VB6 apps? My guess is that there is some problem that is occurring the first time you use frmClientCommon1. Did you do what the error message suggested and look at the InnerException? The inner exception should provide you with more useful information about what is going wrong. Also, as a general tip, think about what is different between the dev environment and production environment. Different connection strings needed? Missing data files? Registry settings? Basically anything that might be set up differently.

    Visual Basic data-structures debugging help lounge workspace

  • vb.net, check array elements?
    G Gideon Engelberth

    You should probably encapsulate this into a function and return false for the first one that does not match and return true if you get to the end of the array without finding one that does not match. Incidentally, if you are using .NET 3.5, the built in All extension method from LINQ will do just that.

    .NET (Core and Framework) question csharp data-structures

  • Code problem or exceeded array limits?
    G Gideon Engelberth

    As an alternative to the sort and merge approach, you may also try using a Dictionary/HashSet. If you have .NET 3.5 available, you could use the Except extension method (which I understand uses a HashSet internally) like so:

    Dim temp = ArrayB.Select(AddressOf Double.Parse) _
    .Except(ArrayA.Select(AddressOf Double.Parse)) _
    .ToArray()

    If you don't have the LINQ methods, you could do this yourself:

    Dim parsedToRemove As New Dictionary(Of Double, Double)
    Dim noDuplicates As New List(Of Double)

    For Each parsedA In Array.ConvertAll(ArrayA, AddressOf Double.Parse)
    If Not parsedToRemove.ContainsKey(parsedA) Then
    parsedToRemove.Add(parsedA, parsedA)
    End If
    Next
    For Each parsedB In Array.ConvertAll(ArrayB, AddressOf Double.Parse)
    If Not parsedToRemove.ContainsKey(parsedB) Then
    noDuplicates.Add(parsedB)
    End If
    Next
    'noDuplicates now has the values in B not in A

    .NET (Core and Framework) help data-structures performance question

  • Problem with If Then Else End If block in Visual Studio 2008 code editor
    G Gideon Engelberth

    I'm not sure where you get that idea. In VB a line in the form:

    If condition Then statement

    is a self-contained, single statement If that does not have a matching End If I have not heard that this will change in VB2010. What I have heard is that in some cases, you will not need an _ to extend a statement to a second line, but this is kind of the reverse issue.

    Visual Basic csharp visual-studio regex help
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups