Monday, April 11, 2011

SocketException on Windows XP home edition on connect: an invalid argument was supplied

Hi,

Our software needs to connect to an server and we do that with use of an TCPclient. 50+ systems (all Windows XP pro) are using the software and have no problem with connecting. The software also has been tested on windows vista an Windows 7 beta.

Today there are some external people here for training and one of them has a laptop with Windows XP Home edition, which fails to connect to the server with SocketExeption "an invalid argument was supplied". (windows socket exception code: 10022)

However, when we try to telnet to that ip and port on the same laptop we can make a connection.

The code to connect is very basic:

m_client = new TcpClient();
m_client.Connect(System.Net.IPAddress.Parse(host), port);

Are there any additional socketoptions we have to set on Windows XP Home edition?

About his system: Windows XP Home edition version 2002 Service pack 2 One network-card active: Broadcom 440x 10/100 Integrated Controller

From stackoverflow
  • Just for people who wonder. We never got the time to further investigate the issue. It seemed to be a problem with the host's pc...

Use LINQ to concatenate multiple rows into single row (CSV property)

I'm looking for the LINQ equivalent to the Sybase's LIST() or MySQL's group_concat()

It'll convert:

User  Hobby
--------------
Bob   Football 
Bob   Golf 
Bob   Tennis 
Sue   Sleeping 
Sue   Drinking

To:

User  Hobby
--------------
Bob   Football, Golf, Tennis 
Sue   Sleeping, Drinking
From stackoverflow
  • That's the GroupBy operator. Are you using LINQ to Objects?

    Here's an example:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class Test
    {
        static void Main()
        {
            var users = new[]
            {
                new { User="Bob", Hobby="Football" },
                new { User="Bob", Hobby="Golf" },
                new { User="Bob", Hobby="Tennis" },
                new { User="Sue", Hobby="Sleeping" },
                new { User="Sue", Hobby="Drinking" },
            };
    
            var groupedUsers = users.GroupBy(user => user.User);
    
            foreach (var group in groupedUsers)
            {
                Console.WriteLine("{0}: ", group.Key);
                foreach (var entry in group)
                {
                    Console.WriteLine("  {0}", entry.Hobby);
                }
            }
        }
    }
    

    That does the grouping - can you manage the rest yourself?

    Hosam Aly : It's also possible to replace the inner loop with `String.Join(", ", group.ToArray())`, as long as the number of elements is not very large.
    John Paul Jones : Thanks! I'm going to learn LINQ myself instead of constantly bugging you ;-)
    Carter : Am I the only one that noticed the man is into sports while the woman's hobbies are sleeping and drinking? You're terrible Jon Skeet!
    Jon Skeet : @Carter: They're not *my* examples...
    Carter : Ha, you're right, my bad. Still funny.
  • See if this solution helps you:

    List<User> users = new List<User>() 
    { 
        new User {Name = "Bob", Hobby = "Football" },
        new User {Name = "Bob", Hobby = "Golf"},
        new User {Name = "Bob", Hobby = "Tennis"},
        new User {Name = "Sue", Hobby = "Sleeping"},
        new User {Name = "Sue", Hobby = "Drinking"}
    };
    
    var groupedUsers = from u in users
             group u by u.Name into g
             select new
             {
                 Name = g.First<User>().Name,
                 Hobby = g.Select(u => u.Hobby)
             };
    
    
    foreach (var user in groupedUsers)
    {
        Console.WriteLine("Name: {0}", user.Name);
        foreach (var hobby in user.Hobby)
        {
            Console.WriteLine("Hobby: {0}", hobby);
        }
    }
    
  • re the _concat aspect of your question, using:

    static class EnumerableExtensions 
    {  
        public static String AsJoined( this IEnumerable<String> enumerable )
        {
            return AsJoined( enumerable, "," );
        }
    
        public static String AsJoined( this IEnumerable<String> enumerable, String separator )
        {
            return String.Join( separator, enumerable.ToArray() );
        }
    }
    

    The outputting foreach in bruno conde and Jon Skeet's answers can become:

    Console.WriteLine( "User:\tHobbies");
    foreach ( var group in groupedUsers )
        Console.WriteLine( "{0}:\t{1}", group.Key, group.Select( g => g.Hobby ).AsJoined( ", " ) );
    

    ... and you'll get the precise result output format you asked for (yes, I know the others have already solved your problem, but its hard to resist!)

  • To do it in one Linq Statement. There is no way I'd recommend the code, but it shows that it could be done.

                var groupedUsers = from user in users
                               group user by user.User into userGroup
                               select new
                               {
                                   User = userGroup.Key,
                                   userHobies =
                                       userGroup.Aggregate((a, b) => 
                                           new { User = a.User, Hobby = (a.Hobby + ", " + b.Hobby) }).Hobby
                               }
                                ;
            foreach (var x in groupedUsers)
            {
                Debug.WriteLine(String.Format("{0} {1}", x.User, x.userHobies));
            }
    

How do I add a namespace while doing XmlSerialization with an XmlWriter?

I am using the XmlWriter in conjunction with Xml Serialization. I am able to output the XML fine, but how to include the xmlns attribute with the XmlWriter seems to be escaping me.

To write the start of the document I use the following:

    Writer.WriteStartDocument();
    Writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");

With my XmlWriter created I then loop through SitemapNodes I have created them and write them to the underlying stringbuilder through serialization like this:

    foreach (uk.co.andrewrea.SitemapNode node in List)
    {
        Serializer.Serialize(Writer, node);
    }

As I say this works fine BUT the above namespace for the root element is not included. Every time I try to physically write the attribute, xmlns, I get an exception that the xmlns is reserved by the system for XML use, so basically I cannot use.

I know how to do this using the XmlTextWriter and also using the XmlDocument class but i need to understand how I achieve this using the XmlWriter and through Serialization.

The following attempt also throws the exception about that namespace being reserved.

foreach (uk.co.andrewrea.SitemapNode node in List)
{
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
      ns.Add("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

      Serializer.Serialize(Writer, node, ns);
}

Exception Details: System.ArgumentException: Prefix "xmlns" is reserved for use by XML.
From stackoverflow
  • You can add the namespace to the XmlSerialization attributes, e.g.:

    [XmlElement(
    ElementName = "Members",
    Namespace = "http://www.cpandl.com")]
    public Employee[] Employees;
    

    if you have control over the code.

    REA_ANDREW : I have included that now, but still the attribute is not output.
    REA_ANDREW : Right I am being DUMB, I was viewing the output in firefox, WHICH hides these attibutes. Viewing the source showed that my oriignal code actually works fine. :-( Thanks for your help.

How to architect DAL for WebService exposure?

We have a highly specialized DAL which sits over our DB. Our apps need to use this DAL to correctly operate against this DB.

The generated DAL (which sits on some custom base classes) has various 'Rec' classes (Table1Rec, Table2Rec) each of which represents the record structure of a given table.

Here is a sample Pseudo-class...

Public Class SomeTableRec
    Private mField1 As String
    Private mField1isNull As Boolean
    Private mField2 As Integer
    Private mField2isNull As Boolean

    Public Sub New()
        mField1isNull = True
        mField2isNull = True
    End Sub
    Public Property Field1() As String
        Get
            Return mField1
        End Get
        Set(ByVal value As String)
            mField1 = value
            mField1isNull = False
        End Set
    End Property
    Public ReadOnly Property Field1isNull() As Boolean
        Get
            Return mField1isNull
        End Get
    End Property
    Public Property Field2() As Integer
        Get
            Return mField2
        End Get
        Set(ByVal value As Integer)
            mField2 = value
            mField2isNull = False
        End Set
    End Property
    Public ReadOnly Property Field2isNull() As Boolean
        Get
            Return mField2isNull
        End Get
    End Property
End Class

Each class has properties for each of the fields... Thus I can write...

Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
Table2Rec.Field2 = 500

Where a field can accept a NULL value, there is an additional property which indicates if the value is currently null.

Thus....

Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
If Table1Rec.Field1Null then 
    ' This clearly is not true
End If
If Table1Rec.Field2Null then 
    ' This will be true
End If

This works because the constructor of the class sets all NULLproperties to True and the setting of any FieldProperty will cause the equivalent NullProperty to be set to false.

I have recently had the need to expose my DAL over the web through a web service (which I of course intend to secure) and have discovered that while the structure of the 'Rec' class remains intact over the web... All logic is lost..

If someone were to run the previous piece of code remotely they would notice that neither condition would prove true as there is no client side code which sets null to true.

I get the feeling I have architected this all wrong, but cannot see how I should improve it.

What is the correct way to architect this?

From stackoverflow
  • Web services are designed to expose operation(methods) & data contracts but not internal implementation logic. This is a "good thing" in the world of service-oriented architecture. The scenario you describe is a remote/distributed object architecture. Web services will not support what you are trying to do. Please see this post for more information.

  • Not sure if I fully understand the question, but you can have nullable data types in XML.

    So this...

    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    
    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Public Class Testing
         Inherits System.Web.Services.WebService
    
        <WebMethod()> _
       Public Function GetObjects() As Generic.List(Of TestObject)
            Dim list As New Generic.List(Of TestObject)
            list.Add(New TestObject(Nothing, "Empty ID Object"))
            list.Add(New TestObject(1, "Full ID Object"))
            list.Add(New TestObject(2, Nothing))
            Return list
        End Function
    
        Public Class TestObject
            Public Sub New()
                _name = String.Empty
                _id = Nothing
            End Sub
            Public Sub New(ByVal id As Nullable(Of Integer), ByVal name As String)
                _name = name
                _id = id
            End Sub
            Private _name As String
            Public Property Name() As String
                Get
                    Return _name
                End Get
                Set(ByVal value As String)
                    _name = value
                End Set
            End Property
    
            Private _id As Nullable(Of Integer)
            Public Property ID() As Nullable(Of Integer)
                Get
                    Return _id
                End Get
                Set(ByVal value As Nullable(Of Integer))
                    _id = value
                End Set
            End Property
        End Class
    
    End Class
    

    outputs this (with nullable areas)

    <?xml version="1.0" encoding="utf-8" ?> 
    <ArrayOfTestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
     <TestObject>
      <Name>Empty ID Object</Name> 
      <ID xsi:nil="true" /> 
     </TestObject>
     <TestObject>
      <Name>Full ID Object</Name> 
      <ID>1</ID> 
     </TestObject>
     <TestObject>
      <ID>2</ID> 
     </TestObject>
    </ArrayOfTestObject>
    

Which Qt DLL's should I copy to make my program stand-alone?

Hi, I'm trying to make a distribution directory with my application. I've copied several Qt DLLs to that directory, and the program seems to be working, with one exception: it doesn't seem to find SQL plugin for SQLite. Copying qtsqlite.dll to the directory, doesn't allow my application to open or create SQLite files. What must be the direcotry structure or which additional files need to be copied so that the program can read the database?

From stackoverflow
  • Most probably, the qtsqlite.dll itself depends on original SQLite DLL's which you probably need to copy as well.

    Don't forget to include an LGP license copy in your distribution as well as pointers to the original download ressources of the libs you include and their sources. To stay with the law :-)

  • you can use depends.exe to see exactly what the dependencies of your exe are and make sure they're all included.

    Also, read this page about qt plugins. they are supposed to be in a specific directory called "plugins" and not in the main directory with all the other dlls.

    dwj : By default the application will use its start-up directory as the plugins directory; you need to put the drivers in a base class directory name: e.g., app_dir/sqldrivers.
  • Thanks to the link @shoosh provided, I was able to fix the problem. I needed to create sqldrivers subdirectory in the distribution dir with qsqlite.dll library inside. But that was just step one. Do you have any tips and resources on creating a full-blown Windows installer? I'm mainly a Linux programmer so this area is unknown to me.

    ypnos : Perhaps NSIS is a good starting point for you: http://nsis.sourceforge.net/ It is open source and scriptable. Good for Linux programmers :-D

WiFi iPhone Application

Hi im working on an iPhone application which requires communication between 2 devices through WiFi.

Can somebody please help me by providing a simple iphone application code for the same which is able to communicate data between the devices...i hv gone through the "witap application" available on the developers site but wasnt able to understand it...

please help..

From stackoverflow

TextBox Validation in VB.NET and Windows Forms

I'm using the following code to validate the text entered by user. It works perfectly fine. But I want to add the backspace feature so as to allow the user to delete the wrongly entered number.

I have tried a couple of things and they worked but before last digit (after the decimal point) i.e. it does not allows to delete after the number has been completely entered. number is being entered in the format: 12313213.45

What shall I do?

Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress

    'validation '
    Dim KeyAscii As Short = Asc(e.KeyChar)
    If Not ((KeyAscii >= System.Windows.Forms.Keys.D0 And KeyAscii <= System.Windows.Forms.Keys.D9) Or (KeyAscii = System.Windows.Forms.Keys.Back) Or Chr(KeyAscii) = "." Or (Chr(KeyAscii) Like "[ ]")) Then
        KeyAscii = 0
        TextBox5.Focus()
    End If
    If KeyAscii = 0 Then
        e.Handled = True
    End If

    If TextBox5.Text.IndexOf(".") >= 0 And e.KeyChar = "." Then
        e.Handled = True
    End If

    If TextBox5.Text.IndexOf(".") > 0 Then
        If TextBox5.SelectionStart > TextBox5.Text.IndexOf(".") Then
            If TextBox5.Text.Length - TextBox5.Text.IndexOf(".") = 3 Then
                e.Handled = True
            End If
        End If
    End If
End Sub
From stackoverflow
  • There is a much easier way to validate this. Try convert the text in the edit box to a floating point number. If you catch an exception, the number is not valid.

    Trying to validate keystroke by keystroke is going to cause you many headaches.

    dmce : Is it wise to use exceptions to perform a task?
    Pavel Minaev : No, which is why you use `Decimal.TryParse` instead.
  • Don't try and validate keystrokes one at a time.
    1) You have just found that backspace requires more code, now add support for cut/copy and paste, and the delete key and typing replaces selection. The code is not nice.
    2) It will only confuse the user. Or worse, they try and type a . seperated date into your field, you force that date into a legitimate number by ignoring the second . and they have now entered something totally wrong and your program won't tell them.
    The validating event of the textbox is where this sort of logic should go. It will fire when the focus moves to another control (whose CausesValidation property is true, this allows cancel buttons to be clicked even if the current control is not in a valid state).
    In the validating event you can do all the checks you need to and cancel the event if the data is not valid, as well as displaying whatever message you need to. To validate the value I would suggest Single.TryParse to start with, then if the conversion succeeds you can continue to do any range checks that you require. TryParse is better than @Bork's suggestion because it is easier to read and avoids the throwing/catching of un-necessary exceptions.

    EDIT: Just noticed you are also restricting the length of the entered text. You can do that by setting the MaxLength property of the TextBox.

  • An even better way is to use a control that supports decimals (if that is you're using something like infragistics, componentone, devexpress, etc.) The user gets visual cues and can do neat things like click the arrows to advance the numbers.

    If you're using plain old winforms, have a look at the masked edit control.

    Personally I find it HUGELY irritating when applications try to correct me and i'm not done entering data. It's much more user friendly to let the user finish and then notify them if there are any problems.

    Pavel Minaev : Actually, the stock `NumericUpDown` WinForms control can handle decimal fractions - but it requires you to specify how many decimal places to show, and won't let user input more than that.
  • I think the link below should give you exactly what you're after:

    Numeric TextBox

    Although it requires a fair amount of code to handle validation on each keypress, it's certainly possible, and the code above seems to handle delete, backspace, copy/pasting etc.

  • Or use a regular expression for the tough stuff

  • Yeah, or just make that nested if...then block look like this:

    If Textbox5.Text.IndexOf(".") > 0 Then
        If Textbox5.SelectionStart > Textbox5.Text.IndexOf(".") Then
            If Textbox5.Text.Length - Textbox5.Text.IndexOf(".") = 3 Then
                If KeyAscii <> System.Windows.Forms.Keys.Back Then e.Handled = True
            End If
        End If
    End If
    
  • txtMobil.Text = Format(txtMobil.Text, "###-###-####")